Travis build: 807 [ci skip]

This commit is contained in:
Travis CI
2018-01-01 17:05:39 +00:00
parent ceaf1857ac
commit 44b05b9a98
4 changed files with 125 additions and 14 deletions

View File

@ -8,21 +8,35 @@ Use `String.replace()` with a regular expression to replace `^` with `**`, `Stri
Use `Array.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression.
Numeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations.
``` js
```js
const solveRPN = rpn => {
const OPERATORS = {'*' : (a,b) => a * b, '+' : (a,b) => a + b, '-' : (a,b) => a - b, '/' : (a,b) => a / b, '**': (a,b) => a ** b};
const [stack,solve] = [[],rpn.replace(/\^/g,'**').split(/\s+/g).filter(el => !/\s+/.test(el) && el !== '')];
const OPERATORS = {
'*': (a, b) => a * b,
'+': (a, b) => a + b,
'-': (a, b) => a - b,
'/': (a, b) => a / b,
'**': (a, b) => a ** b
};
const [stack, solve] = [
[],
rpn
.replace(/\^/g, '**')
.split(/\s+/g)
.filter(el => !/\s+/.test(el) && el !== '')
];
solve.forEach(symbol => {
if(!isNaN(parseFloat(symbol)) && isFinite(symbol)) {stack.push(symbol)}
else if (Object.keys(OPERATORS).includes(symbol)) {
const [a,b] = [stack.pop(),stack.pop()];
stack.push(OPERATORS[symbol](parseFloat(b),parseFloat(a)))
} else { throw `${symbol} is not a recognized symbol` }
}
)
if(stack.length === 1) return stack.pop()
else throw `${rpn} is not a proper RPN. Please check it and try again`
}
if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {
stack.push(symbol);
} else if (Object.keys(OPERATORS).includes(symbol)) {
const [a, b] = [stack.pop(), stack.pop()];
stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));
} else {
throw `${symbol} is not a recognized symbol`;
}
});
if (stack.length === 1) return stack.pop();
else throw `${rpn} is not a proper RPN. Please check it and try again`;
};
```
```js