github.com/livekit/protocol@v1.16.1-0.20240517185851-47e4c6bba773/utils/math.go (about)

     1  // Copyright 2023 LiveKit, Inc.
     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 utils
    16  
    17  import (
    18  	"time"
    19  
    20  	"golang.org/x/exp/constraints"
    21  )
    22  
    23  type Numeric interface {
    24  	constraints.Signed | constraints.Unsigned | time.Duration
    25  }
    26  
    27  func Max[T Numeric](vs ...T) T {
    28  	return Least(func(a, b T) bool { return a > b }, vs...)
    29  }
    30  
    31  func Min[T Numeric](vs ...T) T {
    32  	return Least(func(a, b T) bool { return a < b }, vs...)
    33  }
    34  
    35  func Most[T Numeric](less func(a, b T) bool, vs ...T) T {
    36  	return Least(func(a, b T) bool { return !less(a, b) }, vs...)
    37  }
    38  
    39  func Least[T Numeric](less func(a, b T) bool, vs ...T) T {
    40  	if len(vs) == 0 {
    41  		return 0
    42  	}
    43  	v := vs[0]
    44  	for i := 1; i < len(vs); i++ {
    45  		if less(vs[i], v) {
    46  			v = vs[i]
    47  		}
    48  	}
    49  	return v
    50  }