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 ]
@@ -194,6 +194,14 @@ join(['pen', 'pineapple', 'apple', 'pen']); //"pen,pineapple,apple,pen"
))();
const squareIt = arr => mapObject(arr, a => a * a);
squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
+
maxN
Returns the n maximum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in descending order).
Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in descending order. Use Array.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
+
maxN([1, 2, 3]); // [3]
+maxN([1, 2, 3], 2); // [3,2]
+maxN([1, 2, 3], 4); // [3,2,1]
+
minN
Returns the n minimum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in ascending order).
Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in ascending order. Use Array.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
+
minN([1, 2, 3]); // [1]
+minN([1, 2, 3], 2); // [1,2]
+minN([1, 2, 3], 4); // [1,2,3]
nthElement
Returns the nth element of an array.
Use Array.slice() to get an array containing the nth element at the first place. If the index is out of bounds, return []. Omit the second argument, n, to get the first element of the array.
const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
nthElement(['a', 'b', 'c'], 1); // 'b'
nthElement(['a', 'b', 'b'], -3); // 'a'
@@ -626,6 +634,14 @@ elo([1200, 1200], 64); // [1232, 1168]
return data.reduce((a, b) => helperGcd(a, b));
};
gcd(8, 36); // 4
+
geometricProgression
Initializes an array containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step. Returns an error if step equals 1.
Use Array.from(), Math.log() and Math.floor() to create an array of the desired length, Array.map() to fill with the desired values in a range. Omit the second argument, start, to use a default value of 1. Omit the third argument, step, to use a default value of 2.
const geometricProgression = (end, start = 1, step = 2) =>
+ Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map(
+ (v, i) => start * step ** i
+ );
+
geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256]
+geometricProgression(256, 3); //[3, 6, 12, 24, 48, 96, 192]
+geometricProgression(256, 1, 4); //[1, 4, 16, 64, 256]
+geometricProgression(256, 2, 1); //Gives error
hammingDistance
Calculates the Hamming distance between two values.
Use XOR operator (^) to find the bit difference between the two numbers, convert to a binary string using toString(2). Count and return the number of 1s in the string, using match(/1/g).
const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;
hammingDistance(2, 3); // 1
inRange
Checks if the given number falls within the given range.
Use arithmetic comparison to check if the given number is in the specified range. If the second parameter, end, is not specified, the range is considered to be from 0 to start.
const inRange = (n, start, end = null) => {
@@ -908,6 +924,17 @@ mask(1234567890, -4, '$'); // '1234$$$$$$'
);
};
palindrome('taco cat'); // true
+
pluralize
If num is greater than 1 returns the plural form of the given string, else return the singular form.
Check if num is positive. Throw an appropriate Error if not, return the appropriate string otherwise. Omit the third argument, items, to use a default plural form same as item suffixed with a single 's'.
const pluralize = (num, item, items = item + 's') =>
+ num <= 0
+ ? (() => {
+ throw new Error(`'num' should be >= 1. Value povided was ${num}.`);
+ })()
+ : num === 1 ? item : items;
+
pluralize(1, 'apple', 'apples'); // 'apple'
+pluralize(3, 'apple', 'apples'); // 'apples'
+pluralize(2, 'apple'); // 'apples'
+pluralize(0, 'apple', 'apples'); // Gives error
+pluralize(-3, 'apple', 'apples'); // Gives error
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;
};
@@ -1152,31 +1179,4 @@ console.log(sdbm('age')); // 808122783
yesNo('yes'); // true
yesNo('No'); // false
yesNo('Foo', true); // true
-
Uncategorized
geometricProgression
Initializes an array containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step. Returns an error if step equals 1.
Use Array.from(), Math.log() and Math.floor() to create an array of the desired length, Array.map() to fill with the desired values in a range. Omit the second argument, start, to use a default value of 1. Omit the third argument, step, to use a default value of 2.
const geometricProgression = (end, start = 1, step = 2) =>
- Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map(
- (v, i) => start * step ** i
- );
-
geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256]
-geometricProgression(256, 3); //[3, 6, 12, 24, 48, 96, 192]
-geometricProgression(256, 1, 4); //[1, 4, 16, 64, 256]
-geometricProgression(256, 2, 1); //Gives error
-
maxN
Returns the n maximum elements from the provided array. If n is greater than or equal to the provided array's length than return the original array(sorted in descending order).
Sort's the array's shallow copy in descending order and returns the first n elements
Skip the second argument to get a single element(in the form of a array)
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
-
maxN([1, 2, 3]); // [3]
-maxN([1, 2, 3], 2); // [3,2]
-maxN([1, 2, 3], 4); // [3,2,1]
-
minN
Returns the n minimum elements from the provided array. If n is greater than or equal to the provided array's length than return the original array(sorted in ascending order).
Sort's the array's shallow copy in ascending order and returns the first n elements
Skip the second argument to get a single element(in the form of a array)
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
-
minN([1, 2, 3]); // [1]
-minN([1, 2, 3], 2); // [1,2]
-minN([1, 2, 3], 4); // [1,2,3]
-
pluralize
If num is greater than 1 returns the plural form of the given string, else return the singular form.
Check if num is positive. Throw an appropriate Error if not, return the appropriate string otherwise. Omit the third argument, items, to use a default plural form same as item suffixed with a single 's'.
const pluralize = (num, item, items = item + 's') =>
- num <= 0
- ? (() => {
- throw new Error(`'num' should be >= 1. Value povided was ${num}.`);
- })()
- : num === 1 ? item : items;
-
pluralize(1, 'apple', 'apples'); // 'apple'
-pluralize(3, 'apple', 'apples'); // 'apples'
-pluralize(2, 'apple'); // 'apples'
-pluralize(0, 'apple', 'apples'); // Gives error
-pluralize(-3, 'apple', 'apples'); // Gives error
\ No newline at end of file