Last active
January 29, 2021 18:42
-
-
Save AyAyEm/99fb130b08e5b38914ffea493a7540f8 to your computer and use it in GitHub Desktop.
Alphabetical sort
This file contains 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
function alphabeticalSort< | |
T extends Map<unknown, unknown>, | |
>(collection: T): (T extends Map<infer K, infer V> ? [K, V] : never)[]; | |
function alphabeticalSort< | |
T extends Array<unknown>, | |
>(collection: T): T; | |
function alphabeticalSort< | |
T extends Set<unknown>, | |
>(collection: T): (T extends Array<infer V> ? V : never)[]; | |
function alphabeticalSort< | |
K extends string, | |
T extends Array<K> | Map<K, unknown> | Set<K> | |
>(collection: T): unknown[] { | |
const sort = (keyA: string, keyB: string): number => { | |
if (!keyA || keyB.length < 1) return 1; | |
if (!keyB || keyA.length < 1) return -1; | |
if (keyA[0] === keyB[0]) { | |
return sort(keyA.slice(1), keyB.slice(1)); | |
} | |
return (keyA.toUpperCase().codePointAt(0) ?? 0) - (keyB.toUpperCase().codePointAt(0) ?? 0); | |
} | |
return [...collection].sort((keyA, keyB) => { | |
if (keyA === keyB) return 0; | |
if (keyA instanceof Array) return sort(keyA[0], keyB[0]); | |
return sort(keyA as K, keyB as K); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment