github.com/searKing/golang/go@v1.2.74/exp/math/compare.go (about) 1 // Copyright 2023 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package math 6 7 import ( 8 "golang.org/x/exp/constraints" 9 ) 10 11 // Compare returns an integer comparing two elements. 12 // The result will be 0 if a == b, -1 if a < b, and +1 if a > b. 13 // This implementation places NaN values before any others, by using: 14 // 15 // a < b || (math.IsNaN(a) && !math.IsNaN(b)) 16 func Compare[E constraints.Ordered](a E, b E) int { 17 if a < b || IsNaN(a) && !IsNaN(b) { 18 return -1 19 } 20 21 if a == b || IsNaN(a) && IsNaN(b) { 22 return 0 23 } 24 return 1 25 } 26 27 // IsNaN is a copy of math.IsNaN to avoid a dependency on the math package. 28 func IsNaN[E constraints.Ordered](f E) bool { 29 return f != f 30 }