Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function calculator(stringCalculation) {
- let numbers = []
- let operators = []
- let currentDigits = ''
- for (let i = 0; i < stringCalculation.length + 1; i++) {
- const currentSymbol = stringCalculation[i]
- const number = parseInt(currentSymbol)
- if (Number.isNaN(number)) {
- numbers.push(parseInt(currentDigits))
- if (currentSymbol) {
- operators.push(currentSymbol)
- }
- currentDigits = ''
- } else {
- currentDigits += number
- }
- }
- return calculate(numbers, operators)
- }
- function action(arg1, arg2, operator) {
- switch (operator) {
- case "+":
- return arg1 + arg2;
- case "*":
- return arg1 * arg2;
- }
- return 0
- }
- const symbolPriority = ['*', ':', '+', '-']
- function calculate(numbers, operators) {
- if (operators.length === 0) {
- return numbers[0] ?? 0
- }
- let index = -1
- for (let i = 0; i < symbolPriority.length; i++) {
- index = operators.indexOf(symbolPriority[i])
- if (index !== -1) {
- break;
- }
- }
- const firstPart = numbers.slice(0, index)
- const secondPart = numbers.slice(index + 2)
- const localResult = action(numbers[index], numbers[index + 1], operators[index])
- const newNumbers = [...firstPart, localResult, ...secondPart]
- const newOperators = operators.filter((_, idx) => idx !== index)
- return calculate(newNumbers, newOperators)
- }
- calculator("11+2*3+4")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement