Last active
October 15, 2021 11:50
-
-
Save robertocarroll/b1e3a111d4133a5f63627cb660342080 to your computer and use it in GitHub Desktop.
Object literals as an alternative to if else and switch: https://betterprogramming.pub/dont-use-if-else-and-switch-in-javascript-use-object-literals-c54578566ba0
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
//https://gist.github.com/jogilvyt/22f1628d4c2853df1113f8e28096fde0 | |
function getTranslationMap(rhyme) { | |
const rhymes = { | |
"apples and pears": "Stairs", | |
"hampstead heath": "Teeth", | |
"loaf of bread": "Head", | |
"pork pies": "Lies", | |
"whistle and flute": "Suit", | |
}; | |
return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found"; | |
} | |
//https://gist.github.com/jogilvyt/6490ace2eb90c096b1f90992c3ac2623#file-rhyming-slang-two-js | |
function getTranslation(rhyme) { | |
switch (rhyme.toLowerCase()) { | |
case "apples and pears": | |
return "Stairs"; | |
case "hampstead heath": | |
return "Teeth"; | |
case "loaf of bread": | |
return "Head"; | |
case "pork pies": | |
return "Lies"; | |
case "whistle and flute": | |
return "Suit"; | |
default: | |
return "Rhyme not found"; | |
} | |
} | |
//https://gist.github.com/jogilvyt/eb1daabea713bd04d5d5d7b893608182#file-rhyming-slang-one-js | |
function getTranslation(rhyme) { | |
if (rhyme.toLowerCase() === "apples and pears") { | |
return "Stairs"; | |
} else if (rhyme.toLowerCase() === "hampstead heath") { | |
return "Teeth"; | |
} else if (rhyme.toLowerCase() === "loaf of bread") { | |
return "Head"; | |
} else if (rhyme.toLowerCase() === "pork pies") { | |
return "Lies"; | |
} else if (rhyme.toLowerCase() === "whistle and flute") { | |
return "Suit"; | |
} | |
return "Rhyme not found"; | |
} | |
//pass a function as the value to your object keys and execute the response | |
function calculate(num1, num2, action) { | |
const actions = { | |
add: (a, b) => a + b, | |
subtract: (a, b) => a - b, | |
multiply: (a, b) => a * b, | |
divide: (a, b) => a / b, | |
}; | |
return actions[action]?.(num1, num2) ?? "Calculation is not recognised"; | |
} | |
//use optional chaining (the ?. in the last line of code) to only execute the response if it is defined. Otherwise, fall through to the default return string. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment