Last active
June 13, 2018 14:11
-
-
Save aesedepece/51de9d06c91439a8a92c517b408d62ff to your computer and use it in GitHub Desktop.
Safely reverting keys and values in a JS object
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
const enum ChainType { | |
test, | |
main | |
} | |
const prefixToChainType: stringToNumber = { | |
"wit": ChainType.main, | |
"twit": ChainType.test | |
} | |
const chainTypeToPrefix = kvSwap(prefixToChainType) | |
type stringToNumber = { [key: string]: number } | |
type numberToString = { [key: number]: string } | |
type stringToString = { [key: string]: string } | |
function kvSwap(obj: numberToString): stringToNumber | |
function kvSwap(obj: stringToNumber): numberToString | |
function kvSwap(obj: stringToString): stringToString | |
function kvSwap(obj: stringToNumber | numberToString | stringToString): any { | |
return Object | |
.entries(obj) | |
.reduce((acc, [key, value]) => { | |
return {...acc, [value]: key} | |
}, {}) | |
} | |
const prefix = chainTypeToPrefix[ChainType.main] | |
const chainType = prefixToChainType[prefix] | |
const a = kvSwap({a: console.log}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment