Last active
March 16, 2019 21:53
-
-
Save SimplGy/46fb534366c6316111dca8f47d2d1162 to your computer and use it in GitHub Desktop.
sort keys of an object using an array index as rank, with TypeScript
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
export interface SomeShape { | |
b: string, | |
c: string, | |
a: string, | |
} | |
// Specify your sort order here | |
const rank: Array<keyof SomeShape> = ['a', 'b', 'c']; | |
export function sortedKvpString(obj: SomeShape) { | |
return Object.entries(obj) | |
.sort(([a_], [b_]) => { | |
const a = a_ as keyof SomeShape; // #ts workaround :.( | |
const b = b_ as keyof SomeShape; | |
return rank.indexOf(a) - rank.indexOf(b); | |
}) | |
.map(([key, val])=> `* ${key}: ${val}`) | |
.join('\n'); | |
} | |
// Now we know they'll print in order: | |
console.log( | |
sortedKvpString({b: 3, a: 1, c: 5}) // prints a,b,c | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment