Skip to content

Instantly share code, notes, and snippets.

@gabrieleromanato
Created May 29, 2022 11:16
Show Gist options
  • Save gabrieleromanato/de012955610563ef820e249bdbf0d96a to your computer and use it in GitHub Desktop.
Save gabrieleromanato/de012955610563ef820e249bdbf0d96a to your computer and use it in GitHub Desktop.
Emulating switch/case Statements in Python with Dictionaries: JavaScript version
'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