Last active
February 1, 2026 11:07
-
-
Save VenkataRaju/780f7d606335e29d817874b93a626632 to your computer and use it in GitHub Desktop.
Java style JS comparator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| let log = console.log.bind (console); | |
| class Comparator | |
| { | |
| static #strCompararor = (f, s) => f.localeCompare (s); | |
| static #numComparator = (f, s) => | |
| (f < s) ? -1 : (f > s) ? 1 : 0; | |
| static strComparator () { return this.#strCompararor; } | |
| static numComparator () { return this.#numComparator; } | |
| static #IC = class IC | |
| { | |
| #extractorAndConparators; | |
| constructor (keyExtractor, keyComparator) | |
| { | |
| this.#extractorAndComparators = [[keyExtractor, keyComparator]]; | |
| } | |
| thenComparing (keyExtractor, keyComparator = Comparator.strComparator ()) | |
| { | |
| this.#extractorAndComparators.push ([keyExtractor, keyComparator]); | |
| return this; | |
| } | |
| compare (ob1, ob2) | |
| { | |
| for (let [keyExtractor, keyComparator] of this.#extractorAndComparators) | |
| { | |
| let key1 = keyExtractor (ob1); | |
| let key2 = keyExtractor (ob2); | |
| let res = keyComparator (key1, key2); | |
| if (res !== 0) | |
| return res; | |
| } | |
| return 0; | |
| } | |
| } | |
| static comparing (keyExtractor, keyComparator = Comparator.strComparator ()) | |
| { | |
| return new Comparator.#IC (keyExtractor, keyComparator); | |
| } | |
| constructor () | |
| { | |
| throw new Error ("Shouldn't be called"); | |
| } | |
| compare () | |
| { | |
| throw new Error ("Shouldn't be called"); | |
| } | |
| } | |
| let f = { a : { a1: 'ACCC', b : {b1: 10, name: 'Bbc'} } }; | |
| let s = { a : { a1: 'CCC', b : {b1: 10, name: 'Bbc'} } }; | |
| log (Comparator.comparing (o => o.a.a1) | |
| .thenComparing (o => o.a.b.b1, Comparator.numComparator ()) | |
| .thenComparing (o => o.a.b.name) | |
| .compare (f, s)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment