import { compare } from "https://deno.land/x/ayonli_jsext@v0.9.72/object/index.ts";
Compares two values, returns -1
if a < b
, 0
if a === b
and 1
if a > b
.
If the values are not comparable, a TypeError is thrown.
- Primitive types such as
string
,number
,bigint
,boolean
,null
andundefined
are supported. - Objects that implement the Comparable interface are supported.
- Objects whose
valueOf
method returns primitive values are supported. - When primitive values are compared, they must be of the same type.
- When objects are compared, they must be instances of the same class or one class is
a super class of the other, or the objects are created with an object literal or
Object.create(null)
of the same structure.
NaN
is not comparable and will throw an error if compared.
Examples
Example 1
Example 1
// compare primitive values
import { compare } from "@ayonli/jsext/object";
console.log(compare("a", "b")); // -1
console.log(compare(2, 1)); // 1
console.log(compare(1n, 1n)); // 0
Example 2
Example 2
// compare objects
import { compare } from "@ayonli/jsext/object";
import { Comparable } from "@ayonli/jsext/types"
class Person implements Comparable {
constructor(public name: string, public age: number) {}
compareTo(other: Person): -1 | 0 | 1 {
return this.age === other.age ? 0 : this.age < other.age ? -1 : 1;
}
}
const person1 = new Person("Alice", 25);
const person2 = new Person("Bob", 30);
const person3 = new Person("Charlie", 25);
console.log(compare(person1, person2)); // -1
console.log(compare(person1, person3)); // 0