github.com/searKing/golang/go@v1.2.117/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  	"cmp"
     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  //
    17  // Deprecated: Use [cmp.Compare] instead since go1.21.
    18  func Compare[E cmp.Ordered](a E, b E) int {
    19  	if a < b || IsNaN(a) && !IsNaN(b) {
    20  		return -1
    21  	}
    22  
    23  	if a == b || IsNaN(a) && IsNaN(b) {
    24  		return 0
    25  	}
    26  	return 1
    27  }
    28  
    29  // Reverse returns the reverse comparison for cmp, as cmp(b, a).
    30  func Reverse[E cmp.Ordered](cmp func(a E, b E) int) func(a E, b E) int {
    31  	return func(a E, b E) int {
    32  		return cmp(b, a)
    33  	}
    34  }
    35  
    36  // IsNaN is a copy of math.IsNaN to avoid a dependency on the math package.
    37  func IsNaN[E cmp.Ordered](f E) bool {
    38  	return f != f
    39  }