Created
June 19, 2017 12:51
-
-
Save lmuntaner/5905ff41ca7dc46f5a7c7088ae1c8715 to your computer and use it in GitHub Desktop.
Calculator
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
// 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