Skip to content

Instantly share code, notes, and snippets.

@ismkdc
Created May 19, 2022 19:55
Show Gist options
  • Save ismkdc/9e985bcf9fb7978153bbb1b709da9f10 to your computer and use it in GitHub Desktop.
Save ismkdc/9e985bcf9fb7978153bbb1b709da9f10 to your computer and use it in GitHub Desktop.
export const CalcMachine = () => {
let state = '';
const operators = ['+', '-', '*', '/'];
const sumReducer = (acc, value) => acc + value;
const mulReducer = (acc, value) => acc * value;
const divReducer = (acc, value) => acc / value;
const subReducer = (acc, value) => acc - value;
const sum = (args) => args.reduce(sumReducer);
const mul = (args) => args.reduce(mulReducer);
const div = (args) => args.reduce(divReducer);
const sub = (args) => args.reduce(subReducer);
const calcDict = { '+': sum, '-': sub, '*': mul, '/': div };
const parseOperator = (value) => operators.find(op => value.includes(op));
const calculate = (operator) => {
if (operator) {
const arr = state.split(operator).map(el => parseInt(el));
return calcDict[operator](arr);
}
}
const push = (value) => {
let existOperator = parseOperator(state);
let newOperator = parseOperator(value);
if (existOperator && newOperator) {
state = calculate(existOperator)
}
state += value;
return state;
}
const reset = () => {
state = '';
return state;
}
const parseAndCalculate = () => {
const operator = parseOperator(state);
state = calculate(operator);
return state;
}
return { push, reset, parseAndCalculate }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment