go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/data/sortby/sortby.go (about) 1 // Copyright 2017 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 // Package sortby provides a succinct way to generate correctly-behaved Less 16 // functions for use with the stdlib 'sort' package. 17 package sortby 18 19 // LessFn is the type of the function which compares element i with element j of 20 // a given slice. Unlike the stdlib sort interpretation of this function, 21 // a LessFn in sortby should only compare a single field in your datastructure's 22 // elements. Multiple LessFns can be composed with Chain to create a composite 23 // Less implementation to pass to sort. 24 type LessFn func(i, j int) bool 25 26 // Chain is a list of LessFns, each of which sorts a single aspect of your 27 // object. Nil LessFns will be ignored. 28 type Chain []LessFn 29 30 // Use is a sort-compatible LessFn that actually executes the full chain of 31 // comparisons. 32 func (c Chain) Use(i, j int) bool { 33 for _, less := range c { 34 if less == nil { 35 continue 36 } 37 if less(i, j) { 38 return true 39 } else if less(j, i) { 40 return false 41 } 42 } 43 return false 44 }