Created
May 29, 2022 11:16
-
-
Save gabrieleromanato/de012955610563ef820e249bdbf0d96a to your computer and use it in GitHub Desktop.
Emulating switch/case Statements in Python with Dictionaries: JavaScript version
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
'use strict'; | |
/* | |
https://www.youtube.com/watch?v=gllUwQnYVww | |
Emulating switch/case Statements in Python with Dictionaries | |
*/ | |
const execFunc = (operand = 'add', a = 1, b = 1) => { | |
const getOperand = (name, obj) => { | |
if(typeof obj[name] !== 'function') { | |
return () => {}; | |
} | |
return obj[name](); | |
}; | |
return getOperand(operand, { | |
add: () => a + b, | |
sub: () => a - b, | |
mul: () => a * b, | |
div: () => a / b | |
}); | |
}; | |
const operations = [ | |
{ | |
operand: 'add', | |
values: [2, 1] | |
}, | |
{ | |
operand: 'sub', | |
values: [2, 1] | |
}, | |
{ | |
operand: 'mul', | |
values: [2, 3] | |
}, | |
{ | |
operand: 'div', | |
values: [2, 2] | |
} | |
]; | |
for(let op of operations) { | |
let { operand } = op; | |
let [a, b] = op.values; | |
console.log(execFunc(operand, a, b)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment