diff --git a/README.md b/README.md index 923ee362e..143e0710b 100644 --- a/README.md +++ b/README.md @@ -276,6 +276,15 @@ +### _Uncategorized_ + +
+View contents + +* [`solveRPN`](#solverpn) + +
+ --- ## 🔌 Adapter @@ -4848,6 +4857,60 @@ yesNo('Foo', true); // true
[⬆ Back to top](#table-of-contents) +--- + ## _Uncategorized_ + +### solveRPN + +Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation). +Throws appropriate errors if there are unrecognized symbols or the expression is wrong. + +Use a dictionary, `OPERATORS` to specify each operator's matching mathematical operation. +Use `String.replace()` with a regular expression to replace `^` with `**`, `String.split()` to tokenize the string and `Array.filter()` to remove empty tokens. +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 +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 !== '') + ]; + 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`; +}; +``` + +```js +solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5 +solveRPN('3 5 6 + *'); //33 +solveRPN('2 4 / 5 6 - *'); //-0.5 +solveRPN('2 3 ^'); //8 +solveRPN('2 3 ^'); //8 +``` + +
[⬆ back to top](#table-of-contents) + ## Collaborators diff --git a/docs/index.html b/docs/index.html index c5d582434..bd81c05f8 100644 --- a/docs/index.html +++ b/docs/index.html @@ -59,7 +59,7 @@ wrapper.appendChild(box); box.appendChild(el); }); - }

 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

call

Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

Use a closure to call a stored key with stored arguments.

const call = (key, ...args) => context => context[key](...args);
+    }

 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

 

Adapter

call

Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

Use a closure to call a stored key with stored arguments.

const call = (key, ...args) => context => context[key](...args);
 
Promise.resolve([1, 2, 3])
   .then(call('map', x => 2 * x))
   .then(console.log); //[ 2, 4, 6 ]
@@ -1038,4 +1038,37 @@ console.log(sdbm('age')); // 808122783
 yesNo('yes'); // true
 yesNo('No'); // false
 yesNo('Foo', true); // true
+

Uncategorized

solveRPN

Solves the given mathematical expression in reverse polish notation. Throws appropriate errors if there are unrecognized symbols or the expression is wrong.

Use a dictionary, OPERATORS to specify each operator's matching mathematical operation. Use String.replace() with a regular expression to replace ^ with **, String.split() to tokenize the string and Array.filter() to remove empty tokens. 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.

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 !== '')
+  ];
+  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`;
+};
+
solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5
+solveRPN('3 5 6 + *'); //33
+solveRPN('2 4 / 5 6 - *'); //-0.5
+solveRPN('2 3 ^'); //8
+solveRPN('2 3 ^'); //8
 

\ No newline at end of file diff --git a/snippets/solveRPN.md b/snippets/solveRPN.md index 059c0ac36..099be512a 100644 --- a/snippets/solveRPN.md +++ b/snippets/solveRPN.md @@ -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 diff --git a/tag_database b/tag_database index c4f3cd421..39940d0f1 100644 --- a/tag_database +++ b/tag_database @@ -137,6 +137,7 @@ shuffle:array similarity:array size:object sleep:function +solveRPN:uncategorized sortCharactersInString:string sortedIndex:array speechSynthesis:browser