Skip to content

Instantly share code, notes, and snippets.

@lmuntaner
Created June 19, 2017 12:51
Show Gist options
  • Save lmuntaner/5905ff41ca7dc46f5a7c7088ae1c8715 to your computer and use it in GitHub Desktop.
Save lmuntaner/5905ff41ca7dc46f5a7c7088ae1c8715 to your computer and use it in GitHub Desktop.
Calculator
// Calculator
const operations = {
'+': (...nums) => nums.reduce((acc, num) => acc + num),
'*': (...nums) => nums.reduce((acc, num) => acc * num),
}
const calculatorCreator = (additionalOperations = {}) => {
const calculator = (...elements) => {
const operator = elements[elements.length-1];
let inputs = elements.slice(0, elements.length -1);
inputs = inputs.map(input => Array.isArray(input)
? calculator(...input)
: input
);
const totalOpeations = Object.assign({}, operations, additionalOperations);
return totalOpeations[operator](...inputs);
};
return calculator;
}
const simpleCalculator = calculatorCreator();
console.log(simpleCalculator(2, 5, '+')) // 7
console.log(simpleCalculator(3, [2, 5, '*'], '+')); // 13
console.log(simpleCalculator([2, 5, 4, '+'], 3, '*')); // 33
const input1 = [1, 2, '+']; // 3
const input2 = [input1, 3, '*']; // 9
console.log(simpleCalculator(input2, 2, '*')); // 18
const options = {
mean: (...nums) => (nums.reduce((acc, num) => acc + num) / nums.length),
};
console.log(calculatorCreator(options)(1, 2, 4, 'mean'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment