π°Compare
Comparable Interface
The Comparable interface represents an object that can be compared to another object of the same type. It provides a method compareTo that returns a negative number if the current object is less than the other, zero if they are equal, or a positive number if the current object is greater than the other.
To make an object comparable it needs to implement the Comparable interface:
class FooBar implements Comparable<FooBar>{
constructor(private readonly code:number) {
}
compareTo(other: FooBar): number {
return this.code - other.code;
}
}
const foo = new FooBar(1);
const bar = new FooBar(2);
foo.compareTo(bar);
// Output: -1Examples:
Number Comparison
String Comparison
Date Comparison
Comparator Interface
The Comparator interface represents a generic comparator function for comparing two elements of the same type. It provides a method compare that returns a negative number if the first element is less than the second, a positive number if the first element is greater than the second, or zero if they are equal.
Examples:
Number Comparator
String Comparator
InlineComparator Interface
The InlineComparator interface represents a comparator function that can be used to compare two objects. It is a simpler alternative to the Comparator interface.
Examples:
Number InlineComparator
String InlineComparator
Prototype Extensions
Katxupa extends the prototypes of Number, String, and Boolean to include a compareTo method. This allows for convenient comparisons between primitive types.
Examples:
Boolean Comparison
Number Comparison
String Comparison
These extensions enhance the native JavaScript types with a consistent and convenient way to perform comparisons.
Last updated