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 ]
@@ -622,6 +622,39 @@ median([0, 10, -2, 7]); // 3.5
randomNumberInRange(2, 10); // 6.0211363285087005
round
Rounds a number to a specified amount of digits.
Use Math.round() and template literals to round the number to the specified number of digits. Omit the second argument, decimals to round to an integer.
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
round(1.005, 2); // 1.01
+
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
standardDeviation
Returns the standard deviation of an array of numbers.
Use Array.reduce() to calculate the mean, variance and the sum of the variance of the values, the variance of the values, then determine the standard deviation. You can omit the second argument to get the sample standard deviation or set it to true to get the population standard deviation.
const standardDeviation = (arr, usePopulation = false) => {
const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length;
return Math.sqrt(
@@ -1038,37 +1071,4 @@ 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