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 ]
@@ -517,17 +517,6 @@ lcm([1, 3, 4], 5); // 60
median([0, 10, -2, 7]); // 3.5
min
Returns the minimum value in an array.
Use Math.min() combined with the spread operator (...) to get the minimum value in the array.
const min = arr => Math.min(...[].concat(...arr));
min([10, 1, 5]); // 1
-
palindrome
Returns true if the given string is a palindrome, false otherwise.
Convert string toLowerCase() and use replace() to remove non-alphanumeric characters from it. Then, split('') into individual characters, reverse(), join('') and compare to the original, unreversed string, after converting it tolowerCase().
const palindrome = str => {
- const s = str.toLowerCase().replace(/[\W_]/g, '');
- return (
- s ===
- s
- .split('')
- .reverse()
- .join('')
- );
-};
-
palindrome('taco cat'); // true
percentile
Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value.
Use Array.reduce() to calculate how many numbers are below the value and how many are the same value and apply the percentile formula.
const percentile = (arr, val) =>
100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length;
percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6); // 55
@@ -688,6 +677,17 @@ countVowels('gym'); // 0
fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name'
fromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized'
fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'
+
palindrome
Returns true if the given string is a palindrome, false otherwise.
Convert string toLowerCase() and use replace() to remove non-alphanumeric characters from it. Then, split('') into individual characters, reverse(), join('') and compare to the original, unreversed string, after converting it tolowerCase().
const palindrome = str => {
+ const s = str.toLowerCase().replace(/[\W_]/g, '');
+ return (
+ s ===
+ s
+ .split('')
+ .reverse()
+ .join('')
+ );
+};
+
palindrome('taco cat'); // true
repeatString
Repeats a string n times using String.repeat()
If no string is provided the default is "" and the default number of times is 2.
const repeatString = (str = '', num = 2) => {
return num >= 0 ? str.repeat(num) : str;
};