Created
May 19, 2022 19:55
-
-
Save ismkdc/9e985bcf9fb7978153bbb1b709da9f10 to your computer and use it in GitHub Desktop.
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
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