UNPKG

2.66 kBMarkdownView Raw
1<!-- Note: This file is automatically generated from source code comments. Changes made in this file will be overridden. -->
2
3# Function compareNatural
4
5Compare two values of any type in a deterministic, natural way.
6
7For numeric values, the function works the same as `math.compare`.
8For types of values that can't be compared mathematically,
9the function compares in a natural way.
10
11For numeric values, x and y are considered equal when the relative
12difference between x and y is smaller than the configured epsilon.
13The function cannot be used to compare values smaller than
14approximately 2.22e-16.
15
16For Complex numbers, first the real parts are compared. If equal,
17the imaginary parts are compared.
18
19Strings are compared with a natural sorting algorithm, which
20orders strings in a "logic" way following some heuristics.
21This differs from the function `compare`, which converts the string
22into a numeric value and compares that. The function `compareText`
23on the other hand compares text lexically.
24
25Arrays and Matrices are compared value by value until there is an
26unequal pair of values encountered. Objects are compared by sorted
27keys until the keys or their values are unequal.
28
29
30## Syntax
31
32```js
33math.compareNatural(x, y)
34```
35
36### Parameters
37
38Parameter | Type | Description
39--------- | ---- | -----------
40`x` | * | First value to compare
41`y` | * | Second value to compare
42
43### Returns
44
45Type | Description
46---- | -----------
47number | Returns the result of the comparison: 1 when x > y, -1 when x < y, and 0 when x == y.
48
49
50## Examples
51
52```js
53math.compareNatural(6, 1) // returns 1
54math.compareNatural(2, 3) // returns -1
55math.compareNatural(7, 7) // returns 0
56
57math.compareNatural('10', '2') // returns 1
58math.compareText('10', '2') // returns -1
59math.compare('10', '2') // returns 1
60
61math.compareNatural('Answer: 10', 'Answer: 2') // returns 1
62math.compareText('Answer: 10', 'Answer: 2') // returns -1
63math.compare('Answer: 10', 'Answer: 2')
64 // Error: Cannot convert "Answer: 10" to a number
65
66const a = math.unit('5 cm')
67const b = math.unit('40 mm')
68math.compareNatural(a, b) // returns 1
69
70const c = math.complex('2 + 3i')
71const d = math.complex('2 + 4i')
72math.compareNatural(c, d) // returns -1
73
74math.compareNatural([1, 2, 4], [1, 2, 3]) // returns 1
75math.compareNatural([1, 2, 3], [1, 2]) // returns 1
76math.compareNatural([1, 5], [1, 2, 3]) // returns 1
77math.compareNatural([1, 2], [1, 2]) // returns 0
78
79math.compareNatural({a: 2}, {a: 4}) // returns -1
80```
81
82
83## See also
84
85[compare](compare.md),
86[compareText](compareText.md)
87
\No newline at end of file