Last active
August 26, 2020 09:29
-
-
Save munkacsitomi/49085e8abf83219c1ac594676d721ae8 to your computer and use it in GitHub Desktop.
How to swap keys and values in an Object and how to handle different types in JS
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
const swapKeyVal = (obj) => Object.assign({}, ...Object.entries(obj).map(([a,b]) => ({ [b]: a }))); | |
const getNumber = (num) => { | |
const isStringType = typeof num === 'string'; | |
const isNumberType = typeof num === 'number'; | |
let hasNumber = false; | |
let keyVal = { one: 1, two: 2, three: 3 }; | |
if (!isStringType && !isNumberType) { | |
throw new Error('Unknown type'); | |
} | |
if (isStringType) { | |
hasNumber = Object.keys(keyVal).includes(num); | |
} else if (isNumberType) { | |
keyVal = swapKeyVal(keyVal); | |
hasNumber = Object.keys(keyVal).map(Number).includes(num); | |
} | |
if (!hasNumber) { | |
throw new Error('Unknown number'); | |
} else { | |
return keyVal[num]; | |
} | |
}; | |
console.log(getNumber(1)); // one | |
console.log(getNumber('one')); // 1 | |
console.log(getNumber(4)); // Error: Unknown number | |
console.log(getNumber('four')); // Error: Unknown number | |
console.log(getNumber(null)); // Error: Unknown type |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment