Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/ayonli_jsext/object/index.ts>compare

A JavaScript extension package for building strong and modern applications.
Latest
function compare
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 and undefined 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

// 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

// 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

Parameters

a: string
b: string

Returns

-1 | 0 | 1

Parameters

a: number
b: number

Returns

-1 | 0 | 1

Parameters

a: bigint
b: bigint

Returns

-1 | 0 | 1

Parameters

a: boolean
b: boolean

Returns

-1 | 0 | 1

Type Parameters

T extends { valueOf():
| string
| number
| bigint
| boolean
; }

Returns

-1 | 0 | 1

Parameters

a: unknown
b: unknown

Returns

0 | never