Travis build: 352

This commit is contained in:
Travis CI
2017-12-27 09:04:32 +00:00
parent b74eb9d9bd
commit bc0bc5acac
2 changed files with 178 additions and 182 deletions

180
README.md
View File

@ -186,7 +186,7 @@ Given a key and a set of arguments, call them when given a context. Primarily us
Use a closure to call a stored key with stored arguments. Use a closure to call a stored key with stored arguments.
```js ```js
const call = ( key, ...args ) => context => context[ key ]( ...args ); 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 ] Promise.resolve( [ 1, 2, 3 ] ).then( call('map', x => 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
const map = call.bind(null, 'map') const map = call.bind(null, 'map')
@ -203,7 +203,7 @@ Changes a function that accepts an array into a variadic function.
Given a function, return a closure that collects all inputs into an array-accepting function. Given a function, return a closure that collects all inputs into an array-accepting function.
```js ```js
const collectInto = fn => ( ...args ) => fn( args ); const collectInto = fn => (...args) => fn(args);
/* /*
const Pall = collectInto( Promise.all.bind(Promise) ) const Pall = collectInto( Promise.all.bind(Promise) )
let p1 = Promise.resolve(1) let p1 = Promise.resolve(1)
@ -222,7 +222,7 @@ Flip takes a function as an argument, then makes the first argument the last
Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest. Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.
```js ```js
const flip = fn => (...args) => fn(args.pop(), ...args) const flip = fn => (...args) => fn(args.pop(), ...args);
/* /*
let a = {name: 'John Smith'} let a = {name: 'John Smith'}
let b = {} let b = {}
@ -302,10 +302,10 @@ Calculates the greatest common denominator (gcd) of an array of numbers.
Use `Array.reduce()` and the `gcd` formula (uses recursion) to calculate the greatest common denominator of an array of numbers. Use `Array.reduce()` and the `gcd` formula (uses recursion) to calculate the greatest common denominator of an array of numbers.
```js ```js
const arrayGcd = arr =>{ const arrayGcd = arr => {
const gcd = (x, y) => !y ? x : gcd(y, x % y); const gcd = (x, y) => !y ? x : gcd(y, x % y);
return arr.reduce((a,b) => gcd(a,b)); return arr.reduce((a, b) => gcd(a, b));
} };
// arrayGcd([1,2,3,4,5]) -> 1 // arrayGcd([1,2,3,4,5]) -> 1
// arrayGcd([4,8,12]) -> 4 // arrayGcd([4,8,12]) -> 4
``` ```
@ -319,11 +319,11 @@ Calculates the lowest common multiple (lcm) of an array of numbers.
Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the lowest common multiple of an array of numbers. Use `Array.reduce()` and the `lcm` formula (uses recursion) to calculate the lowest common multiple of an array of numbers.
```js ```js
const arrayLcm = arr =>{ const arrayLcm = arr => {
const gcd = (x, y) => !y ? x : gcd(y, x % y); const gcd = (x, y) => !y ? x : gcd(y, x % y);
const lcm = (x, y) => (x*y)/gcd(x, y); const lcm = (x, y) => (x * y) / gcd(x, y);
return arr.reduce((a,b) => lcm(a,b)); return arr.reduce((a, b) => lcm(a, b));
} };
// arrayLcm([1,2,3,4,5]) -> 60 // arrayLcm([1,2,3,4,5]) -> 60
// arrayLcm([4,8,12]) -> 24 // arrayLcm([4,8,12]) -> 24
``` ```
@ -433,7 +433,7 @@ Filters out all values from an array for which the comparator function does not
Use `Array.filter()` and `Array.find()` to find the appropriate values. Use `Array.filter()` and `Array.find()` to find the appropriate values.
```js ```js
const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b))) const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b)));
// differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) -> [1, 1.2] // differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) => Math.round(a) == Math.round(b)) -> [1, 1.2]
``` ```
@ -477,9 +477,9 @@ Use `Array.slice()` to slice the remove the specified number of elements from th
```js ```js
const dropRight = (arr, n = 1) => arr.slice(0, -n); const dropRight = (arr, n = 1) => arr.slice(0, -n);
//dropRight([1,2,3]) -> [1,2] // dropRight([1,2,3]) -> [1,2]
//dropRight([1,2,3], 2) -> [1] // dropRight([1,2,3], 2) -> [1]
//dropRight([1,2,3], 42) -> [] // dropRight([1,2,3], 42) -> []
``` ```
[⬆ back to top](#table-of-contents) [⬆ back to top](#table-of-contents)
@ -517,7 +517,7 @@ Flattens an array.
Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays. Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.
```js ```js
const flatten = arr => [ ].concat( ...arr ); const flatten = arr => [ ].concat(...arr);
// flatten([1,[2],3,4]) -> [1,2,3,4] // flatten([1,[2],3,4]) -> [1,2,3,4]
``` ```
@ -605,7 +605,7 @@ Use `Array((end + 1) - start)` to create an array of the desired length, `Array.
You can omit `start` to use a default value of `0`. You can omit `start` to use a default value of `0`.
```js ```js
const initializeArrayWithRange = (end, start = 0) => const initializeArrayWithRange = (end, start = 0) =>
Array.from({ length: (end + 1) - start }).map((v, i) => i + start); Array.from({ length: (end + 1) - start }).map((v, i) => i + start);
// initializeArrayWithRange(5) -> [0,1,2,3,4,5] // initializeArrayWithRange(5) -> [0,1,2,3,4,5]
// initializeArrayWithRange(7, 3) -> [3,4,5,6,7] // initializeArrayWithRange(7, 3) -> [3,4,5,6,7]
@ -660,8 +660,8 @@ Maps the values of an array to an object using a function, where the key-value p
Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations). Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).
```js ```js
const mapObject = (arr, fn) => const mapObject = (arr, fn) =>
(a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) => (acc[val] = a[1][ind], acc), {}) )) ( ); (a => (a = [arr, arr.map(fn)], a[0].reduce((acc, val, ind) => (acc[val] = a[1][ind], acc), {})))();
/* /*
const squareIt = arr => mapObject(arr, a => a*a) const squareIt = arr => mapObject(arr, a => a*a)
squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 } squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 }
@ -679,7 +679,7 @@ If the index is out of bounds, return `[]`.
Omit the second argument, `n`, to get the first element of the array. Omit the second argument, `n`, to get the first element of the array.
```js ```js
const nthElement = (arr, n=0) => (n>0? arr.slice(n,n+1) : arr.slice(n))[0]; 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','c'],1) -> 'b'
// nthElement(['a','b','b'],-3) -> 'a' // nthElement(['a','b','b'],-3) -> 'a'
``` ```
@ -713,7 +713,7 @@ _(For a snippet that does not mutate the original array see [`without`](#without
const pull = (arr, ...args) => { const pull = (arr, ...args) => {
let argState = Array.isArray(args[0]) ? args[0] : args; let argState = Array.isArray(args[0]) ? args[0] : args;
let pulled = arr.filter((v, i) => !argState.includes(v)); let pulled = arr.filter((v, i) => !argState.includes(v));
arr.length = 0; arr.length = 0;
pulled.forEach(v => arr.push(v)); pulled.forEach(v => arr.push(v));
}; };
@ -740,11 +740,11 @@ Use `Array.push()` to keep track of pulled values
const pullAtIndex = (arr, pullArr) => { const pullAtIndex = (arr, pullArr) => {
let removed = []; let removed = [];
let pulled = arr.map((v, i) => pullArr.includes(i) ? removed.push(v) : v) let pulled = arr.map((v, i) => pullArr.includes(i) ? removed.push(v) : v)
.filter((v, i) => !pullArr.includes(i)) .filter((v, i) => !pullArr.includes(i));
arr.length = 0; arr.length = 0;
pulled.forEach(v => arr.push(v)); pulled.forEach(v => arr.push(v));
return removed; return removed;
} };
// let myArray = ['a', 'b', 'c', 'd']; // let myArray = ['a', 'b', 'c', 'd'];
// let pulled = pullAtIndex(myArray, [1, 3]); // let pulled = pullAtIndex(myArray, [1, 3]);
@ -765,13 +765,13 @@ Use `Array.push()` to keep track of pulled values
```js ```js
const pullAtValue = (arr, pullArr) => { const pullAtValue = (arr, pullArr) => {
let removed = [], let removed = [],
pushToRemove = arr.forEach((v, i) => pullArr.includes(v) ? removed.push(v) : v), pushToRemove = arr.forEach((v, i) => pullArr.includes(v) ? removed.push(v) : v),
mutateTo = arr.filter((v, i) => !pullArr.includes(v)); mutateTo = arr.filter((v, i) => !pullArr.includes(v));
arr.length = 0; arr.length = 0;
mutateTo.forEach(v => arr.push(v)); mutateTo.forEach(v => arr.push(v));
return removed; return removed;
} };
/* /*
let myArray = ['a', 'b', 'c', 'd']; let myArray = ['a', 'b', 'c', 'd'];
let pulled = pullAtValue(myArray, ['b', 'd']); let pulled = pullAtValue(myArray, ['b', 'd']);
@ -793,7 +793,7 @@ The `func` is invoked with three arguments (`value, index, array`).
const remove = (arr, func) => const remove = (arr, func) =>
Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => {
arr.splice(arr.indexOf(val), 1); return acc.concat(val); arr.splice(arr.indexOf(val), 1); return acc.concat(val);
}, []) }, [])
: []; : [];
// remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4] // remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4]
``` ```
@ -859,7 +859,7 @@ Create a `Set` from each array, then use `Array.filter()` on each of them to onl
const symmetricDifference = (a, b) => { const symmetricDifference = (a, b) => {
const sA = new Set(a), sB = new Set(b); const sA = new Set(a), sB = new Set(b);
return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];
} };
// symmetricDifference([1,2,3], [1,2,4]) -> [3,4] // symmetricDifference([1,2,3], [1,2,4]) -> [3,4]
``` ```
@ -947,11 +947,11 @@ If lengths of the argument-arrays vary, `undefined` is used where no value could
const zip = (...arrays) => { const zip = (...arrays) => {
const maxLength = Math.max(...arrays.map(x => x.length)); const maxLength = Math.max(...arrays.map(x => x.length));
return Array.from({length: maxLength}).map((_, i) => { return Array.from({length: maxLength}).map((_, i) => {
return Array.from({length: arrays.length}, (_, k) => arrays[k][i]); return Array.from({length: arrays.length}, (_, k) => arrays[k][i]);
}) });
} };
//zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]] // zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]]
//zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]] // zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]]
``` ```
[⬆ back to top](#table-of-contents) [⬆ back to top](#table-of-contents)
@ -963,7 +963,7 @@ Given an array of valid property identifiers and an array of values, return an o
Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using `Array.reduce()`. Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using `Array.reduce()`.
```js ```js
const zipObject = ( props, values ) => props.reduce( ( obj, prop, index ) => ( obj[prop] = values[index], obj ), {} ) const zipObject = (props, values) => props.reduce((obj, prop, index) => (obj[prop] = values[index], obj), {});
// zipObject(['a','b','c'], [1,2]) -> {a: 1, b: 2, c: undefined} // zipObject(['a','b','c'], [1,2]) -> {a: 1, b: 2, c: undefined}
// zipObject(['a','b'], [1,2,3]) -> {a: 1, b: 2} // zipObject(['a','b'], [1,2,3]) -> {a: 1, b: 2}
``` ```
@ -978,7 +978,7 @@ Converts the given array elements into `<li>` tags and appends them to the list
Use `Array.map()` and `document.querySelector()` to create a list of html tags. Use `Array.map()` and `document.querySelector()` to create a list of html tags.
```js ```js
const arrayToHtmlList = (arr, listID) => arr.map(item => document.querySelector("#"+listID).innerHTML+=`<li>${item}</li>`); const arrayToHtmlList = (arr, listID) => arr.map(item => document.querySelector('#' + listID).innerHTML += `<li>${item}</li>`);
// arrayToHtmlList(['item 1', 'item 2'],'myListID') // arrayToHtmlList(['item 1', 'item 2'],'myListID')
``` ```
@ -1018,7 +1018,7 @@ Detects wether the website is being opened in a mobile device or a desktop/lapto
Use a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop. Use a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop.
```js ```js
const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? "Mobile" : "Desktop"; const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';
// detectDeviceType() -> "Mobile" // detectDeviceType() -> "Mobile"
// detectDeviceType() -> "Desktop" // detectDeviceType() -> "Desktop"
``` ```
@ -1091,8 +1091,8 @@ Use `location.protocol` to get the protocol currently being used. If it's not HT
```js ```js
const httpsRedirect = () => { const httpsRedirect = () => {
if(location.protocol !== "https:") location.replace("https://" + location.href.split("//")[1]); if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
} };
``` ```
[⬆ back to top](#table-of-contents) [⬆ back to top](#table-of-contents)
@ -1155,7 +1155,7 @@ Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).
```js ```js
const JSONToDate = arr => { const JSONToDate = arr => {
const dt = new Date(parseInt(arr.toString().substr(6))); const dt = new Date(parseInt(arr.toString().substr(6)));
return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }` return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
}; };
// JSONToDate(/Date(1489525200000)/) -> "14/3/2017" // JSONToDate(/Date(1489525200000)/) -> "14/3/2017"
``` ```
@ -1170,8 +1170,7 @@ Use `Date.toISOString()`, `split('T')` and `replace()` to convert a date from Am
Throws an error if the passed time cannot be converted to a date. Throws an error if the passed time cannot be converted to a date.
```js ```js
const toEnglishDate = (time) => const toEnglishDate = (time) => { try { return new Date(time).toISOString().split('T')[0].replace(/-/g, '/'); } catch (e) {} };
{try{return new Date(time).toISOString().split('T')[0].replace(/-/g, '/')}catch(e){return}};
// toEnglishDate('09/21/2010') -> '21/09/2010' // toEnglishDate('09/21/2010') -> '21/09/2010'
``` ```
@ -1346,9 +1345,9 @@ Otherwise, return the nearest number in the range.
```js ```js
const clampNumber = (num, lower, upper) => { const clampNumber = (num, lower, upper) => {
if(lower > upper) upper = [lower, lower = upper][0]; if (lower > upper) upper = [lower, lower = upper][0];
return (num>=lower && num<=upper) ? num : ((num < lower) ? lower : upper) return (num >= lower && num <= upper) ? num : ((num < lower) ? lower : upper);
} };
// clampNumber(2, 3, 5) -> 3 // clampNumber(2, 3, 5) -> 3
// clampNumber(1, -1, -5) -> -1 // clampNumber(1, -1, -5) -> -1
// clampNumber(3, 2, 4) -> 3 // clampNumber(3, 2, 4) -> 3
@ -1378,7 +1377,7 @@ Convert the number to a string, using spread operators in ES6(`[...string]`) bui
Use `Array.map()` and `parseInt()` to transform each value to an integer. Use `Array.map()` and `parseInt()` to transform each value to an integer.
```js ```js
const digitize = n => [...''+n].map(i => parseInt(i)); const digitize = n => [...'' + n].map(i => parseInt(i));
// digitize(2334) -> [2, 3, 3, 4] // digitize(2334) -> [2, 3, 3, 4]
``` ```
@ -1408,7 +1407,7 @@ Throws an exception if `n` is a negative number.
```js ```js
const factorial = n => const factorial = n =>
n < 0 ? (() => { throw new TypeError('Negative numbers are not allowed!') })() n < 0 ? (() => { throw new TypeError('Negative numbers are not allowed!'); })()
: n <= 1 ? 1 : n * factorial(n - 1); : n <= 1 ? 1 : n * factorial(n - 1);
// factorial(6) -> 720 // factorial(6) -> 720
``` ```
@ -1438,7 +1437,7 @@ Use a mathematical formula to calculate the number of fibonacci numbers until `n
```js ```js
const fibonacciCountUntilNum = num => const fibonacciCountUntilNum = num =>
Math.ceil(Math.log(num * Math.sqrt(5) + 1/2) / Math.log((Math.sqrt(5)+1)/2)); Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
// fibonacciCountUntilNum(10) -> 7 // fibonacciCountUntilNum(10) -> 7
``` ```
@ -1454,9 +1453,9 @@ Uses a mathematical formula to calculate the length of the array required.
```js ```js
const fibonacciUntilNum = num => { const fibonacciUntilNum = num => {
let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1/2) / Math.log((Math.sqrt(5)+1)/2)); let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
return Array.from({ length: n}).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []); return Array.from({ length: n}).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []);
} };
// fibonacciUntilNum(15) -> [0,1,1,2,3,5,8,13] // fibonacciUntilNum(15) -> [0,1,1,2,3,5,8,13]
``` ```
@ -1500,10 +1499,10 @@ 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`. If the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`.
```js ```js
const inRange = (n, start, end=null) => { const inRange = (n, start, end = null) => {
if(end && start > end) end = [start, start=end][0]; if (end && start > end) end = [start, start = end][0];
return (end == null) ? (n>=0 && n<start) : (n>=start && n<end); return (end == null) ? (n >= 0 && n < start) : (n >= start && n < end);
} };
// inRange(3, 2, 5) -> true // inRange(3, 2, 5) -> true
// inRange(3, 4) -> true // inRange(3, 4) -> true
// inRange(2, 3, 5) -> false // inRange(2, 3, 5) -> false
@ -1519,8 +1518,8 @@ Checks if the given number is an Armstrong number or not.
Convert the given number into an array of digits. Use `Math.pow()` to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`. Convert the given number into an array of digits. Use `Math.pow()` to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`.
```js ```js
const isArmstrongNumber = digits => const isArmstrongNumber = digits =>
( arr => arr.reduce( ( a, d ) => a + Math.pow( parseInt( d ), arr.length ), 0 ) == digits ? true : false )( ( digits+'' ).split( '' ) ); (arr => arr.reduce((a, d) => a + Math.pow(parseInt(d), arr.length), 0) == digits)((digits + '').split(''));
// isArmstrongNumber(1634) -> true // isArmstrongNumber(1634) -> true
// isArmstrongNumber(371) -> true // isArmstrongNumber(371) -> true
// isArmstrongNumber(56) -> false // isArmstrongNumber(56) -> false
@ -1582,9 +1581,9 @@ Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the
The GCD formula uses recursion. The GCD formula uses recursion.
```js ```js
const lcm = (x,y) => { const lcm = (x, y) => {
const gcd = (x, y) => !y ? x : gcd(y, x % y); const gcd = (x, y) => !y ? x : gcd(y, x % y);
return Math.abs(x*y)/(gcd(x,y)); return Math.abs(x * y) / (gcd(x, y));
}; };
// lcm(12,7) -> 84 // lcm(12,7) -> 84
``` ```
@ -1662,13 +1661,13 @@ Generate an array from `2` to the given number. Use `Array.filter()` to filter o
```js ```js
const primes = num => { const primes = num => {
let arr = Array.from({length:num-1}).map((x,i)=> i+2), let arr = Array.from({length: num - 1}).map((x, i) => i + 2),
sqroot = Math.floor(Math.sqrt(num)), sqroot = Math.floor(Math.sqrt(num)),
numsTillSqroot = Array.from({length:sqroot-1}).map((x,i)=> i+2); numsTillSqroot = Array.from({length: sqroot - 1}).map((x, i) => i + 2);
numsTillSqroot.forEach(x => arr = arr.filter(y => ((y%x)!==0)||(y==x))); numsTillSqroot.forEach(x => arr = arr.filter(y => ((y % x) !== 0) || (y == x)));
return arr; return arr;
} };
// primes(10) -> [2,3,5,7] // primes(10) -> [2,3,5,7]
``` ```
[⬆ back to top](#table-of-contents) [⬆ back to top](#table-of-contents)
@ -1707,7 +1706,7 @@ Use `Math.round()` and template literals to round the number to the specified nu
Omit the second argument, `decimals` to round to an integer. Omit the second argument, `decimals` to round to an integer.
```js ```js
const round = (n, decimals=0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
// round(1.005, 2) -> 1.01 // round(1.005, 2) -> 1.01
``` ```
@ -1784,7 +1783,7 @@ Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json`
```js ```js
const fs = require('fs'); const fs = require('fs');
const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)) const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
// JSONToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json' // JSONToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
``` ```
@ -1830,9 +1829,9 @@ const cleanObj = (obj, keysToKeep = [], childIndicator) => {
} else if (!keysToKeep.includes(key)) { } else if (!keysToKeep.includes(key)) {
delete obj[key]; delete obj[key];
} }
 });  });
return obj; return obj;
} };
/* /*
const testObj = {a: 1, b: 2, children: {a: 1, b: 2}} const testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
cleanObj(testObj, ["a"],"children") // { a: 1, children : { a: 1}} cleanObj(testObj, ["a"],"children") // { a: 1, children : { a: 1}}
@ -1970,7 +1969,7 @@ Use destructuring and `toUpperCase()` to capitalize first letter, `...rest` to g
Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase. Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.
```js ```js
const capitalize = ([first,...rest], lowerRest = false) => const capitalize = ([first, ...rest], lowerRest = false) =>
first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
// capitalize('myName') -> 'MyName' // capitalize('myName') -> 'MyName'
// capitalize('myName', true) -> 'Myname' // capitalize('myName', true) -> 'Myname'
@ -2043,9 +2042,9 @@ Repeats a string n times using `String.repeat()`
If no string is provided the default is `""` and the default number of times is 2. If no string is provided the default is `""` and the default number of times is 2.
```js ```js
const repeatString = (str="",num=2) => { const repeatString = (str = '', num = 2) => {
return num >= 0 ? str.repeat(num) : str; return num >= 0 ? str.repeat(num) : str;
} };
// repeatString("abc",3) -> 'abcabcabc' // repeatString("abc",3) -> 'abcabcabc'
// repeatString("abc") -> 'abcabc' // repeatString("abc") -> 'abcabc'
``` ```
@ -2090,10 +2089,10 @@ For more detailed explanation of this Regex, [visit this Site](https://regex101.
```js ```js
const toCamelCase = str => { const toCamelCase = str => {
let s = str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) let s = str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.slice(0,1).toUpperCase() + x.slice(1).toLowerCase()) .map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
.join(''); .join('');
return s.slice(0,1).toLowerCase() + s.slice(1) return s.slice(0, 1).toLowerCase() + s.slice(1);
} };
// toCamelCase("some_database_field_name") -> 'someDatabaseFieldName' // toCamelCase("some_database_field_name") -> 'someDatabaseFieldName'
// toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized' // toCamelCase("Some label that needs to be camelized") -> 'someLabelThatNeedsToBeCamelized'
// toCamelCase("some-javascript-property") -> 'someJavascriptProperty' // toCamelCase("some-javascript-property") -> 'someJavascriptProperty'
@ -2131,11 +2130,11 @@ Break the string into words and combine them using `_` as a separator.
For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1). For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1).
```js ```js
const toSnakeCase = str =>{ const toSnakeCase = str => {
str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase()) .map(x => x.toLowerCase())
.join('_'); .join('_');
} };
// toSnakeCase("camelCase") -> 'camel_case' // toSnakeCase("camelCase") -> 'camel_case'
// toSnakeCase("some text") -> 'some_text' // toSnakeCase("some text") -> 'some_text'
// toSnakeCase("some-javascript-property") -> 'some_javascript_property' // toSnakeCase("some-javascript-property") -> 'some_javascript_property'
@ -2184,7 +2183,7 @@ Returns the first non-null/undefined argument.
Use `Array.find()` to return the first non `null`/`undefined` argument. Use `Array.find()` to return the first non `null`/`undefined` argument.
```js ```js
const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)) const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
// coalesce(null,undefined,"",NaN, "Waldo") -> "" // coalesce(null,undefined,"",NaN, "Waldo") -> ""
``` ```
@ -2212,7 +2211,7 @@ Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for con
`String.slice()` is used to remove `#` from string start since it's added once. `String.slice()` is used to remove `#` from string start since it's added once.
```js ```js
const extendHex = shortHex => const extendHex = shortHex =>
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x+x).join('') '#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x => x + x).join('');
// extendHex('#03f') -> '#0033ff' // extendHex('#03f') -> '#0033ff'
// extendHex('05a') -> '#0055aa' // extendHex('05a') -> '#0055aa'
``` ```
@ -2245,16 +2244,15 @@ const hexToRGB = hex => {
if (h.length === 3) h = [...h].map(x => x + x).join(''); if (h.length === 3) h = [...h].map(x => x + x).join('');
else if (h.length === 8) alpha = true; else if (h.length === 8) alpha = true;
h = parseInt(h, 16); h = parseInt(h, 16);
return 'rgb' + (alpha ? 'a' : '') + '(' return 'rgb' + (alpha ? 'a' : '') + '(' +
+ (h >>> (alpha ? 24 : 16)) + ', ' (h >>> (alpha ? 24 : 16)) + ', ' +
+ ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) + ', ' ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) + ', ' +
+ ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) +
+ (alpha ? `, ${(h & 0x000000ff)}` : '') + ')'; (alpha ? `, ${(h & 0x000000ff)}` : '') + ')';
}; };
// hexToRGB('#27ae60ff') -> 'rgba(39, 174, 96, 255)' // hexToRGB('#27ae60ff') -> 'rgba(39, 174, 96, 255)'
// hexToRGB('27ae60') -> 'rgb(39, 174, 96)' // hexToRGB('27ae60') -> 'rgb(39, 174, 96)'
// hexToRGB('#fff') -> 'rgb(255, 255, 255)' // hexToRGB('#fff') -> 'rgb(255, 255, 255)'
``` ```
[⬆ back to top](#table-of-contents) [⬆ back to top](#table-of-contents)
@ -2351,10 +2349,10 @@ Use `Math.random` to generate a random 24-bit(6x4bits) hexadecimal number. Use b
```js ```js
const randomHexColor = () => { const randomHexColor = () => {
let n = (Math.random()*0xfffff|0).toString(16); let n = (Math.random() * 0xfffff | 0).toString(16);
return '#' + (n.length !== 6 return '#' + (n.length !== 6
? (Math.random()*0xf|0).toString(16) + n : n); ? (Math.random() * 0xf | 0).toString(16) + n : n);
} };
// randomHexColorCode() -> "#e34155" // randomHexColorCode() -> "#e34155"
// randomHexColorCode() -> "#fd73a6" // randomHexColorCode() -> "#fd73a6"
// randomHexColorCode() -> "#4144c6" // randomHexColorCode() -> "#4144c6"
@ -2383,8 +2381,8 @@ Use `console.time()` and `console.timeEnd()` to measure the difference between t
```js ```js
const timeTaken = callback => { const timeTaken = callback => {
console.time('timeTaken'); const r = callback(); console.time('timeTaken'); const r = callback();
console.timeEnd('timeTaken'); return r; console.timeEnd('timeTaken'); return r;
}; };
// timeTaken(() => Math.pow(2, 10)) -> 1024 // timeTaken(() => Math.pow(2, 10)) -> 1024
// (logged): timeTaken: 0.02099609375ms // (logged): timeTaken: 0.02099609375ms
@ -2397,7 +2395,7 @@ const timeTaken = callback => {
Use `toLocaleString()` to convert a float-point arithmetic to the [Decimal mark](https://en.wikipedia.org/wiki/Decimal_mark) form. It makes a comma separated string from a number. Use `toLocaleString()` to convert a float-point arithmetic to the [Decimal mark](https://en.wikipedia.org/wiki/Decimal_mark) form. It makes a comma separated string from a number.
```js ```js
const toDecimalMark = num => num.toLocaleString("en-US"); const toDecimalMark = num => num.toLocaleString('en-US');
// toDecimalMark(12305030388.9087) -> "12,305,030,388.9087" // toDecimalMark(12305030388.9087) -> "12,305,030,388.9087"
``` ```

View File

@ -242,7 +242,7 @@
<div class="card fluid"><div class="section double-padded"><h3 id="call">call</h3></div><div class="section double-padded"> <div class="card fluid"><div class="section double-padded"><h3 id="call">call</h3></div><div class="section double-padded">
<p>Given a key and a set of arguments, call them when given a context. Primarily useful in composition.</p> <p>Given a key and a set of arguments, call them when given a context. Primarily useful in composition.</p>
<p>Use a closure to call a stored key with stored arguments.</p> <p>Use a closure to call a stored key with stored arguments.</p>
<pre><code class="language-js">const call = ( key, ...args ) =&gt; context =&gt; context[ key ]( ...args ); <pre><code class="language-js">const call = (key, ...args) =&gt; context =&gt; context[ key ](...args);
/* /*
Promise.resolve( [ 1, 2, 3 ] ).then( call('map', x =&gt; 2 * x ) ).then( console.log ) //[ 2, 4, 6 ] Promise.resolve( [ 1, 2, 3 ] ).then( call('map', x =&gt; 2 * x ) ).then( console.log ) //[ 2, 4, 6 ]
const map = call.bind(null, 'map') const map = call.bind(null, 'map')
@ -252,7 +252,7 @@ Promise.resolve( [ 1, 2, 3 ] ).then( map( x =&gt; 2 * x ) ).then( console.log )
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="collectinto">collectInto</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="collectinto">collectInto</h3></div><div class="section double-padded">
<p>Changes a function that accepts an array into a variadic function.</p> <p>Changes a function that accepts an array into a variadic function.</p>
<p>Given a function, return a closure that collects all inputs into an array-accepting function.</p> <p>Given a function, return a closure that collects all inputs into an array-accepting function.</p>
<pre><code class="language-js">const collectInto = fn =&gt; ( ...args ) =&gt; fn( args ); <pre><code class="language-js">const collectInto = fn =&gt; (...args) =&gt; fn(args);
/* /*
const Pall = collectInto( Promise.all.bind(Promise) ) const Pall = collectInto( Promise.all.bind(Promise) )
let p1 = Promise.resolve(1) let p1 = Promise.resolve(1)
@ -264,7 +264,7 @@ Pall(p1, p2, p3).then(console.log)
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="flip">flip</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="flip">flip</h3></div><div class="section double-padded">
<p>Flip takes a function as an argument, then makes the first argument the last</p> <p>Flip takes a function as an argument, then makes the first argument the last</p>
<p>Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.</p> <p>Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.</p>
<pre><code class="language-js">const flip = fn =&gt; (...args) =&gt; fn(args.pop(), ...args) <pre><code class="language-js">const flip = fn =&gt; (...args) =&gt; fn(args.pop(), ...args);
/* /*
let a = {name: 'John Smith'} let a = {name: 'John Smith'}
let b = {} let b = {}
@ -315,21 +315,21 @@ arrayMax([1,2,4]) // -&gt; 4
<div class="card fluid"><div class="section double-padded"><h3 id="arraygcd">arrayGcd</h3></div><div class="section double-padded"> <div class="card fluid"><div class="section double-padded"><h3 id="arraygcd">arrayGcd</h3></div><div class="section double-padded">
<p>Calculates the greatest common denominator (gcd) of an array of numbers.</p> <p>Calculates the greatest common denominator (gcd) of an array of numbers.</p>
<p>Use <code>Array.reduce()</code> and the <code>gcd</code> formula (uses recursion) to calculate the greatest common denominator of an array of numbers.</p> <p>Use <code>Array.reduce()</code> and the <code>gcd</code> formula (uses recursion) to calculate the greatest common denominator of an array of numbers.</p>
<pre><code class="language-js">const arrayGcd = arr =&gt;{ <pre><code class="language-js">const arrayGcd = arr =&gt; {
const gcd = (x, y) =&gt; !y ? x : gcd(y, x % y); const gcd = (x, y) =&gt; !y ? x : gcd(y, x % y);
return arr.reduce((a,b) =&gt; gcd(a,b)); return arr.reduce((a, b) =&gt; gcd(a, b));
} };
// arrayGcd([1,2,3,4,5]) -&gt; 1 // arrayGcd([1,2,3,4,5]) -&gt; 1
// arrayGcd([4,8,12]) -&gt; 4 // arrayGcd([4,8,12]) -&gt; 4
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="arraylcm">arrayLcm</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="arraylcm">arrayLcm</h3></div><div class="section double-padded">
<p>Calculates the lowest common multiple (lcm) of an array of numbers.</p> <p>Calculates the lowest common multiple (lcm) of an array of numbers.</p>
<p>Use <code>Array.reduce()</code> and the <code>lcm</code> formula (uses recursion) to calculate the lowest common multiple of an array of numbers.</p> <p>Use <code>Array.reduce()</code> and the <code>lcm</code> formula (uses recursion) to calculate the lowest common multiple of an array of numbers.</p>
<pre><code class="language-js">const arrayLcm = arr =&gt;{ <pre><code class="language-js">const arrayLcm = arr =&gt; {
const gcd = (x, y) =&gt; !y ? x : gcd(y, x % y); const gcd = (x, y) =&gt; !y ? x : gcd(y, x % y);
const lcm = (x, y) =&gt; (x*y)/gcd(x, y); const lcm = (x, y) =&gt; (x * y) / gcd(x, y);
return arr.reduce((a,b) =&gt; lcm(a,b)); return arr.reduce((a, b) =&gt; lcm(a, b));
} };
// arrayLcm([1,2,3,4,5]) -&gt; 60 // arrayLcm([1,2,3,4,5]) -&gt; 60
// arrayLcm([4,8,12]) -&gt; 24 // arrayLcm([4,8,12]) -&gt; 24
</code></pre> </code></pre>
@ -383,7 +383,7 @@ Recursively flatten each element that is an array.</p>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="differencewith">differenceWith</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="differencewith">differenceWith</h3></div><div class="section double-padded">
<p>Filters out all values from an array for which the comparator function does not return <code>true</code>.</p> <p>Filters out all values from an array for which the comparator function does not return <code>true</code>.</p>
<p>Use <code>Array.filter()</code> and <code>Array.find()</code> to find the appropriate values.</p> <p>Use <code>Array.filter()</code> and <code>Array.find()</code> to find the appropriate values.</p>
<pre><code class="language-js">const differenceWith = (arr, val, comp) =&gt; arr.filter(a =&gt; !val.find(b =&gt; comp(a, b))) <pre><code class="language-js">const differenceWith = (arr, val, comp) =&gt; arr.filter(a =&gt; !val.find(b =&gt; comp(a, b)));
// differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) =&gt; Math.round(a) == Math.round(b)) -&gt; [1, 1.2] // differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a,b) =&gt; Math.round(a) == Math.round(b)) -&gt; [1, 1.2]
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="distinctvaluesofarray">distinctValuesOfArray</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="distinctvaluesofarray">distinctValuesOfArray</h3></div><div class="section double-padded">
@ -406,9 +406,9 @@ Returns the remaining elements.</p>
<p>Returns a new array with <code>n</code> elements removed from the right.</p> <p>Returns a new array with <code>n</code> elements removed from the right.</p>
<p>Use <code>Array.slice()</code> to slice the remove the specified number of elements from the right.</p> <p>Use <code>Array.slice()</code> to slice the remove the specified number of elements from the right.</p>
<pre><code class="language-js">const dropRight = (arr, n = 1) =&gt; arr.slice(0, -n); <pre><code class="language-js">const dropRight = (arr, n = 1) =&gt; arr.slice(0, -n);
//dropRight([1,2,3]) -&gt; [1,2] // dropRight([1,2,3]) -&gt; [1,2]
//dropRight([1,2,3], 2) -&gt; [1] // dropRight([1,2,3], 2) -&gt; [1]
//dropRight([1,2,3], 42) -&gt; [] // dropRight([1,2,3], 42) -&gt; []
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="everynth">everyNth</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="everynth">everyNth</h3></div><div class="section double-padded">
<p>Returns every nth element in an array.</p> <p>Returns every nth element in an array.</p>
@ -425,7 +425,7 @@ Returns the remaining elements.</p>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="flatten">flatten</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="flatten">flatten</h3></div><div class="section double-padded">
<p>Flattens an array.</p> <p>Flattens an array.</p>
<p>Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.</p> <p>Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays.</p>
<pre><code class="language-js">const flatten = arr =&gt; [ ].concat( ...arr ); <pre><code class="language-js">const flatten = arr =&gt; [ ].concat(...arr);
// flatten([1,[2],3,4]) -&gt; [1,2,3,4] // flatten([1,[2],3,4]) -&gt; [1,2,3,4]
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="flattendepth">flattenDepth</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="flattendepth">flattenDepth</h3></div><div class="section double-padded">
@ -471,7 +471,7 @@ Use <code>Array.reduce()</code> to create an object, where the keys are produced
<p>Initializes an array containing the numbers in the specified range where <code>start</code> and <code>end</code> are inclusive.</p> <p>Initializes an array containing the numbers in the specified range where <code>start</code> and <code>end</code> are inclusive.</p>
<p>Use <code>Array((end + 1) - start)</code> to create an array of the desired length, <code>Array.map()</code> to fill with the desired values in a range. <p>Use <code>Array((end + 1) - start)</code> to create an array of the desired length, <code>Array.map()</code> to fill with the desired values in a range.
You can omit <code>start</code> to use a default value of <code>0</code>.</p> You can omit <code>start</code> to use a default value of <code>0</code>.</p>
<pre><code class="language-js">const initializeArrayWithRange = (end, start = 0) =&gt; <pre><code class="language-js">const initializeArrayWithRange = (end, start = 0) =&gt;
Array.from({ length: (end + 1) - start }).map((v, i) =&gt; i + start); Array.from({ length: (end + 1) - start }).map((v, i) =&gt; i + start);
// initializeArrayWithRange(5) -&gt; [0,1,2,3,4,5] // initializeArrayWithRange(5) -&gt; [0,1,2,3,4,5]
// initializeArrayWithRange(7, 3) -&gt; [3,4,5,6,7] // initializeArrayWithRange(7, 3) -&gt; [3,4,5,6,7]
@ -498,8 +498,8 @@ You can omit <code>value</code> to use a default value of <code>0</code>.</p>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="mapobject">mapObject</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="mapobject">mapObject</h3></div><div class="section double-padded">
<p>Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.</p> <p>Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value.</p>
<p>Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new <code>Array</code> to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).</p> <p>Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new <code>Array</code> to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations).</p>
<pre><code class="language-js">const mapObject = (arr, fn) =&gt; <pre><code class="language-js">const mapObject = (arr, fn) =&gt;
(a =&gt; (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) =&gt; (acc[val] = a[1][ind], acc), {}) )) ( ); (a =&gt; (a = [arr, arr.map(fn)], a[0].reduce((acc, val, ind) =&gt; (acc[val] = a[1][ind], acc), {})))();
/* /*
const squareIt = arr =&gt; mapObject(arr, a =&gt; a*a) const squareIt = arr =&gt; mapObject(arr, a =&gt; a*a)
squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 } squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 }
@ -510,7 +510,7 @@ squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 }
<p>Use <code>Array.slice()</code> to get an array containing the nth element at the first place. <p>Use <code>Array.slice()</code> to get an array containing the nth element at the first place.
If the index is out of bounds, return <code>[]</code>. If the index is out of bounds, return <code>[]</code>.
Omit the second argument, <code>n</code>, to get the first element of the array.</p> Omit the second argument, <code>n</code>, to get the first element of the array.</p>
<pre><code class="language-js">const nthElement = (arr, n=0) =&gt; (n&gt;0? arr.slice(n,n+1) : arr.slice(n))[0]; <pre><code class="language-js">const nthElement = (arr, n = 0) =&gt; (n &gt; 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
// nthElement(['a','b','c'],1) -&gt; 'b' // nthElement(['a','b','c'],1) -&gt; 'b'
// nthElement(['a','b','b'],-3) -&gt; 'a' // nthElement(['a','b','b'],-3) -&gt; 'a'
</code></pre> </code></pre>
@ -529,7 +529,7 @@ Use <code>Array.length = 0</code> to mutate the passed in an array by resetting
<pre><code class="language-js">const pull = (arr, ...args) =&gt; { <pre><code class="language-js">const pull = (arr, ...args) =&gt; {
let argState = Array.isArray(args[0]) ? args[0] : args; let argState = Array.isArray(args[0]) ? args[0] : args;
let pulled = arr.filter((v, i) =&gt; !argState.includes(v)); let pulled = arr.filter((v, i) =&gt; !argState.includes(v));
arr.length = 0; arr.length = 0;
pulled.forEach(v =&gt; arr.push(v)); pulled.forEach(v =&gt; arr.push(v));
}; };
@ -549,11 +549,11 @@ Use <code>Array.push()</code> to keep track of pulled values</p>
<pre><code class="language-js">const pullAtIndex = (arr, pullArr) =&gt; { <pre><code class="language-js">const pullAtIndex = (arr, pullArr) =&gt; {
let removed = []; let removed = [];
let pulled = arr.map((v, i) =&gt; pullArr.includes(i) ? removed.push(v) : v) let pulled = arr.map((v, i) =&gt; pullArr.includes(i) ? removed.push(v) : v)
.filter((v, i) =&gt; !pullArr.includes(i)) .filter((v, i) =&gt; !pullArr.includes(i));
arr.length = 0; arr.length = 0;
pulled.forEach(v =&gt; arr.push(v)); pulled.forEach(v =&gt; arr.push(v));
return removed; return removed;
} };
// let myArray = ['a', 'b', 'c', 'd']; // let myArray = ['a', 'b', 'c', 'd'];
// let pulled = pullAtIndex(myArray, [1, 3]); // let pulled = pullAtIndex(myArray, [1, 3]);
@ -567,13 +567,13 @@ Use <code>Array.push()</code> to keep track of pulled values</p>
Use <code>Array.length = 0</code> to mutate the passed in an array by resetting it's length to zero and <code>Array.push()</code> to re-populate it with only the pulled values. Use <code>Array.length = 0</code> to mutate the passed in an array by resetting it's length to zero and <code>Array.push()</code> to re-populate it with only the pulled values.
Use <code>Array.push()</code> to keep track of pulled values</p> Use <code>Array.push()</code> to keep track of pulled values</p>
<pre><code class="language-js">const pullAtValue = (arr, pullArr) =&gt; { <pre><code class="language-js">const pullAtValue = (arr, pullArr) =&gt; {
let removed = [], let removed = [],
pushToRemove = arr.forEach((v, i) =&gt; pullArr.includes(v) ? removed.push(v) : v), pushToRemove = arr.forEach((v, i) =&gt; pullArr.includes(v) ? removed.push(v) : v),
mutateTo = arr.filter((v, i) =&gt; !pullArr.includes(v)); mutateTo = arr.filter((v, i) =&gt; !pullArr.includes(v));
arr.length = 0; arr.length = 0;
mutateTo.forEach(v =&gt; arr.push(v)); mutateTo.forEach(v =&gt; arr.push(v));
return removed; return removed;
} };
/* /*
let myArray = ['a', 'b', 'c', 'd']; let myArray = ['a', 'b', 'c', 'd'];
let pulled = pullAtValue(myArray, ['b', 'd']); let pulled = pullAtValue(myArray, ['b', 'd']);
@ -588,7 +588,7 @@ The <code>func</code> is invoked with three arguments (<code>value, index, array
<pre><code class="language-js">const remove = (arr, func) =&gt; <pre><code class="language-js">const remove = (arr, func) =&gt;
Array.isArray(arr) ? arr.filter(func).reduce((acc, val) =&gt; { Array.isArray(arr) ? arr.filter(func).reduce((acc, val) =&gt; {
arr.splice(arr.indexOf(val), 1); return acc.concat(val); arr.splice(arr.indexOf(val), 1); return acc.concat(val);
}, []) }, [])
: []; : [];
// remove([1, 2, 3, 4], n =&gt; n % 2 == 0) -&gt; [2, 4] // remove([1, 2, 3, 4], n =&gt; n % 2 == 0) -&gt; [2, 4]
</code></pre> </code></pre>
@ -626,7 +626,7 @@ This method also works with strings.</p>
<pre><code class="language-js">const symmetricDifference = (a, b) =&gt; { <pre><code class="language-js">const symmetricDifference = (a, b) =&gt; {
const sA = new Set(a), sB = new Set(b); const sA = new Set(a), sB = new Set(b);
return [...a.filter(x =&gt; !sB.has(x)), ...b.filter(x =&gt; !sA.has(x))]; return [...a.filter(x =&gt; !sB.has(x)), ...b.filter(x =&gt; !sA.has(x))];
} };
// symmetricDifference([1,2,3], [1,2,4]) -&gt; [3,4] // symmetricDifference([1,2,3], [1,2,4]) -&gt; [3,4]
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tail">tail</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tail">tail</h3></div><div class="section double-padded">
@ -671,16 +671,16 @@ If lengths of the argument-arrays vary, <code>undefined</code> is used where no
<pre><code class="language-js">const zip = (...arrays) =&gt; { <pre><code class="language-js">const zip = (...arrays) =&gt; {
const maxLength = Math.max(...arrays.map(x =&gt; x.length)); const maxLength = Math.max(...arrays.map(x =&gt; x.length));
return Array.from({length: maxLength}).map((_, i) =&gt; { return Array.from({length: maxLength}).map((_, i) =&gt; {
return Array.from({length: arrays.length}, (_, k) =&gt; arrays[k][i]); return Array.from({length: arrays.length}, (_, k) =&gt; arrays[k][i]);
}) });
} };
//zip(['a', 'b'], [1, 2], [true, false]); -&gt; [['a', 1, true], ['b', 2, false]] // zip(['a', 'b'], [1, 2], [true, false]); -&gt; [['a', 1, true], ['b', 2, false]]
//zip(['a'], [1, 2], [true, false]); -&gt; [['a', 1, true], [undefined, 2, false]] // zip(['a'], [1, 2], [true, false]); -&gt; [['a', 1, true], [undefined, 2, false]]
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="zipobject">zipObject</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="zipobject">zipObject</h3></div><div class="section double-padded">
<p>Given an array of valid property identifiers and an array of values, return an object associating the properties to the values.</p> <p>Given an array of valid property identifiers and an array of values, return an object associating the properties to the values.</p>
<p>Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using <code>Array.reduce()</code>.</p> <p>Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using <code>Array.reduce()</code>.</p>
<pre><code class="language-js">const zipObject = ( props, values ) =&gt; props.reduce( ( obj, prop, index ) =&gt; ( obj[prop] = values[index], obj ), {} ) <pre><code class="language-js">const zipObject = (props, values) =&gt; props.reduce((obj, prop, index) =&gt; (obj[prop] = values[index], obj), {});
// zipObject(['a','b','c'], [1,2]) -&gt; {a: 1, b: 2, c: undefined} // zipObject(['a','b','c'], [1,2]) -&gt; {a: 1, b: 2, c: undefined}
// zipObject(['a','b'], [1,2,3]) -&gt; {a: 1, b: 2} // zipObject(['a','b'], [1,2,3]) -&gt; {a: 1, b: 2}
</code></pre> </code></pre>
@ -688,7 +688,7 @@ If lengths of the argument-arrays vary, <code>undefined</code> is used where no
<div class="card fluid"><div class="section double-padded"><h3 id="arraytohtmllist">arrayToHtmlList</h3></div><div class="section double-padded"> <div class="card fluid"><div class="section double-padded"><h3 id="arraytohtmllist">arrayToHtmlList</h3></div><div class="section double-padded">
<p>Converts the given array elements into <code>&lt;li&gt;</code> tags and appends them to the list of the given id.</p> <p>Converts the given array elements into <code>&lt;li&gt;</code> tags and appends them to the list of the given id.</p>
<p>Use <code>Array.map()</code> and <code>document.querySelector()</code> to create a list of html tags.</p> <p>Use <code>Array.map()</code> and <code>document.querySelector()</code> to create a list of html tags.</p>
<pre><code class="language-js">const arrayToHtmlList = (arr, listID) =&gt; arr.map(item =&gt; document.querySelector(&quot;#&quot;+listID).innerHTML+=`&lt;li&gt;${item}&lt;/li&gt;`); <pre><code class="language-js">const arrayToHtmlList = (arr, listID) =&gt; arr.map(item =&gt; document.querySelector('#' + listID).innerHTML += `&lt;li&gt;${item}&lt;/li&gt;`);
// arrayToHtmlList(['item 1', 'item 2'],'myListID') // arrayToHtmlList(['item 1', 'item 2'],'myListID')
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="bottomvisible">bottomVisible</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="bottomvisible">bottomVisible</h3></div><div class="section double-padded">
@ -707,7 +707,7 @@ If lengths of the argument-arrays vary, <code>undefined</code> is used where no
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="detectdevicetype">detectDeviceType</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="detectdevicetype">detectDeviceType</h3></div><div class="section double-padded">
<p>Detects wether the website is being opened in a mobile device or a desktop/laptop.</p> <p>Detects wether the website is being opened in a mobile device or a desktop/laptop.</p>
<p>Use a regular expression to test the <code>navigator.userAgent</code> property to figure out if the device is a mobile device or a desktop/laptop.</p> <p>Use a regular expression to test the <code>navigator.userAgent</code> property to figure out if the device is a mobile device or a desktop/laptop.</p>
<pre><code class="language-js">const detectDeviceType = () =&gt; /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? &quot;Mobile&quot; : &quot;Desktop&quot;; <pre><code class="language-js">const detectDeviceType = () =&gt; /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';
// detectDeviceType() -&gt; &quot;Mobile&quot; // detectDeviceType() -&gt; &quot;Mobile&quot;
// detectDeviceType() -&gt; &quot;Desktop&quot; // detectDeviceType() -&gt; &quot;Desktop&quot;
</code></pre> </code></pre>
@ -752,8 +752,8 @@ Pass <code>location.search</code> as the argument to apply to the current <code>
<p>Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.</p> <p>Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.</p>
<p>Use <code>location.protocol</code> to get the protocol currently being used. If it's not HTTPS, use <code>location.replace()</code> to replace the existing page with the HTTPS version of the page. Use <code>location.href</code> to get the full address, split it with <code>String.split()</code> and remove the protocol part of the URL.</p> <p>Use <code>location.protocol</code> to get the protocol currently being used. If it's not HTTPS, use <code>location.replace()</code> to replace the existing page with the HTTPS version of the page. Use <code>location.href</code> to get the full address, split it with <code>String.split()</code> and remove the protocol part of the URL.</p>
<pre><code class="language-js">const httpsRedirect = () =&gt; { <pre><code class="language-js">const httpsRedirect = () =&gt; {
if(location.protocol !== &quot;https:&quot;) location.replace(&quot;https://&quot; + location.href.split(&quot;//&quot;)[1]); if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
} };
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="redirect">redirect</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="redirect">redirect</h3></div><div class="section double-padded">
<p>Redirects to a specified URL.</p> <p>Redirects to a specified URL.</p>
@ -788,7 +788,7 @@ Scroll by a fraction of the distance from the top. Use <code>window.requestAnima
<p>Use <code>Date()</code>, to convert dates in JSON format to readable format (<code>dd/mm/yyyy</code>).</p> <p>Use <code>Date()</code>, to convert dates in JSON format to readable format (<code>dd/mm/yyyy</code>).</p>
<pre><code class="language-js">const JSONToDate = arr =&gt; { <pre><code class="language-js">const JSONToDate = arr =&gt; {
const dt = new Date(parseInt(arr.toString().substr(6))); const dt = new Date(parseInt(arr.toString().substr(6)));
return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }` return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
}; };
// JSONToDate(/Date(1489525200000)/) -&gt; &quot;14/3/2017&quot; // JSONToDate(/Date(1489525200000)/) -&gt; &quot;14/3/2017&quot;
</code></pre> </code></pre>
@ -796,8 +796,7 @@ Scroll by a fraction of the distance from the top. Use <code>window.requestAnima
<p>Converts a date from American format to English format.</p> <p>Converts a date from American format to English format.</p>
<p>Use <code>Date.toISOString()</code>, <code>split('T')</code> and <code>replace()</code> to convert a date from American format to the English format. <p>Use <code>Date.toISOString()</code>, <code>split('T')</code> and <code>replace()</code> to convert a date from American format to the English format.
Throws an error if the passed time cannot be converted to a date.</p> Throws an error if the passed time cannot be converted to a date.</p>
<pre><code class="language-js">const toEnglishDate = (time) =&gt; <pre><code class="language-js">const toEnglishDate = (time) =&gt; { try { return new Date(time).toISOString().split('T')[0].replace(/-/g, '/'); } catch (e) {} };
{try{return new Date(time).toISOString().split('T')[0].replace(/-/g, '/')}catch(e){return}};
// toEnglishDate('09/21/2010') -&gt; '21/09/2010' // toEnglishDate('09/21/2010') -&gt; '21/09/2010'
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tomorrow">tomorrow</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="tomorrow">tomorrow</h3></div><div class="section double-padded">
@ -896,9 +895,9 @@ async function sleepyWork() {
If <code>num</code> falls within the range, return <code>num</code>. If <code>num</code> falls within the range, return <code>num</code>.
Otherwise, return the nearest number in the range.</p> Otherwise, return the nearest number in the range.</p>
<pre><code class="language-js">const clampNumber = (num, lower, upper) =&gt; { <pre><code class="language-js">const clampNumber = (num, lower, upper) =&gt; {
if(lower &gt; upper) upper = [lower, lower = upper][0]; if (lower &gt; upper) upper = [lower, lower = upper][0];
return (num&gt;=lower &amp;&amp; num&lt;=upper) ? num : ((num &lt; lower) ? lower : upper) return (num &gt;= lower &amp;&amp; num &lt;= upper) ? num : ((num &lt; lower) ? lower : upper);
} };
// clampNumber(2, 3, 5) -&gt; 3 // clampNumber(2, 3, 5) -&gt; 3
// clampNumber(1, -1, -5) -&gt; -1 // clampNumber(1, -1, -5) -&gt; -1
// clampNumber(3, 2, 4) -&gt; 3 // clampNumber(3, 2, 4) -&gt; 3
@ -914,7 +913,7 @@ Otherwise, return the nearest number in the range.</p>
<p>Converts a number to an array of digits.</p> <p>Converts a number to an array of digits.</p>
<p>Convert the number to a string, using spread operators in ES6(<code>[...string]</code>) build an array. <p>Convert the number to a string, using spread operators in ES6(<code>[...string]</code>) build an array.
Use <code>Array.map()</code> and <code>parseInt()</code> to transform each value to an integer.</p> Use <code>Array.map()</code> and <code>parseInt()</code> to transform each value to an integer.</p>
<pre><code class="language-js">const digitize = n =&gt; [...''+n].map(i =&gt; parseInt(i)); <pre><code class="language-js">const digitize = n =&gt; [...'' + n].map(i =&gt; parseInt(i));
// digitize(2334) -&gt; [2, 3, 3, 4] // digitize(2334) -&gt; [2, 3, 3, 4]
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="distance">distance</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="distance">distance</h3></div><div class="section double-padded">
@ -930,7 +929,7 @@ If <code>n</code> is less than or equal to <code>1</code>, return <code>1</code>
Otherwise, return the product of <code>n</code> and the factorial of <code>n - 1</code>. Otherwise, return the product of <code>n</code> and the factorial of <code>n - 1</code>.
Throws an exception if <code>n</code> is a negative number.</p> Throws an exception if <code>n</code> is a negative number.</p>
<pre><code class="language-js">const factorial = n =&gt; <pre><code class="language-js">const factorial = n =&gt;
n &lt; 0 ? (() =&gt; { throw new TypeError('Negative numbers are not allowed!') })() n &lt; 0 ? (() =&gt; { throw new TypeError('Negative numbers are not allowed!'); })()
: n &lt;= 1 ? 1 : n * factorial(n - 1); : n &lt;= 1 ? 1 : n * factorial(n - 1);
// factorial(6) -&gt; 720 // factorial(6) -&gt; 720
</code></pre> </code></pre>
@ -946,7 +945,7 @@ Use <code>Array.reduce()</code> to add values into the array, using the sum of t
<p>Returns the number of fibonnacci numbers up to <code>num</code>(<code>0</code> and <code>num</code> inclusive).</p> <p>Returns the number of fibonnacci numbers up to <code>num</code>(<code>0</code> and <code>num</code> inclusive).</p>
<p>Use a mathematical formula to calculate the number of fibonacci numbers until <code>num</code>.</p> <p>Use a mathematical formula to calculate the number of fibonacci numbers until <code>num</code>.</p>
<pre><code class="language-js">const fibonacciCountUntilNum = num =&gt; <pre><code class="language-js">const fibonacciCountUntilNum = num =&gt;
Math.ceil(Math.log(num * Math.sqrt(5) + 1/2) / Math.log((Math.sqrt(5)+1)/2)); Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
// fibonacciCountUntilNum(10) -&gt; 7 // fibonacciCountUntilNum(10) -&gt; 7
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="fibonacciuntilnum">fibonacciUntilNum</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="fibonacciuntilnum">fibonacciUntilNum</h3></div><div class="section double-padded">
@ -955,9 +954,9 @@ Use <code>Array.reduce()</code> to add values into the array, using the sum of t
Use <code>Array.reduce()</code> to add values into the array, using the sum of the last two values, except for the first two. Use <code>Array.reduce()</code> to add values into the array, using the sum of the last two values, except for the first two.
Uses a mathematical formula to calculate the length of the array required.</p> Uses a mathematical formula to calculate the length of the array required.</p>
<pre><code class="language-js">const fibonacciUntilNum = num =&gt; { <pre><code class="language-js">const fibonacciUntilNum = num =&gt; {
let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1/2) / Math.log((Math.sqrt(5)+1)/2)); let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
return Array.from({ length: n}).reduce((acc, val, i) =&gt; acc.concat(i &gt; 1 ? acc[i - 1] + acc[i - 2] : i), []); return Array.from({ length: n}).reduce((acc, val, i) =&gt; acc.concat(i &gt; 1 ? acc[i - 1] + acc[i - 2] : i), []);
} };
// fibonacciUntilNum(15) -&gt; [0,1,1,2,3,5,8,13] // fibonacciUntilNum(15) -&gt; [0,1,1,2,3,5,8,13]
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="gcd">gcd</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="gcd">gcd</h3></div><div class="section double-padded">
@ -980,10 +979,10 @@ Count and return the number of <code>1</code>s in the string, using <code>match(
<p>Checks if the given number falls within the given range.</p> <p>Checks if the given number falls within the given range.</p>
<p>Use arithmetic comparison to check if the given number is in the specified range. <p>Use arithmetic comparison to check if the given number is in the specified range.
If the second parameter, <code>end</code>, is not specified, the range is considered to be from <code>0</code> to <code>start</code>.</p> If the second parameter, <code>end</code>, is not specified, the range is considered to be from <code>0</code> to <code>start</code>.</p>
<pre><code class="language-js">const inRange = (n, start, end=null) =&gt; { <pre><code class="language-js">const inRange = (n, start, end = null) =&gt; {
if(end &amp;&amp; start &gt; end) end = [start, start=end][0]; if (end &amp;&amp; start &gt; end) end = [start, start = end][0];
return (end == null) ? (n&gt;=0 &amp;&amp; n&lt;start) : (n&gt;=start &amp;&amp; n&lt;end); return (end == null) ? (n &gt;= 0 &amp;&amp; n &lt; start) : (n &gt;= start &amp;&amp; n &lt; end);
} };
// inRange(3, 2, 5) -&gt; true // inRange(3, 2, 5) -&gt; true
// inRange(3, 4) -&gt; true // inRange(3, 4) -&gt; true
// inRange(2, 3, 5) -&gt; false // inRange(2, 3, 5) -&gt; false
@ -992,8 +991,8 @@ If the second parameter, <code>end</code>, is not specified, the range is consid
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isarmstrongnumber">isArmstrongNumber</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isarmstrongnumber">isArmstrongNumber</h3></div><div class="section double-padded">
<p>Checks if the given number is an Armstrong number or not.</p> <p>Checks if the given number is an Armstrong number or not.</p>
<p>Convert the given number into an array of digits. Use <code>Math.pow()</code> to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return <code>true</code> otherwise <code>false</code>.</p> <p>Convert the given number into an array of digits. Use <code>Math.pow()</code> to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return <code>true</code> otherwise <code>false</code>.</p>
<pre><code class="language-js">const isArmstrongNumber = digits =&gt; <pre><code class="language-js">const isArmstrongNumber = digits =&gt;
( arr =&gt; arr.reduce( ( a, d ) =&gt; a + Math.pow( parseInt( d ), arr.length ), 0 ) == digits ? true : false )( ( digits+'' ).split( '' ) ); (arr =&gt; arr.reduce((a, d) =&gt; a + Math.pow(parseInt(d), arr.length), 0) == digits)((digits + '').split(''));
// isArmstrongNumber(1634) -&gt; true // isArmstrongNumber(1634) -&gt; true
// isArmstrongNumber(371) -&gt; true // isArmstrongNumber(371) -&gt; true
// isArmstrongNumber(56) -&gt; false // isArmstrongNumber(56) -&gt; false
@ -1027,9 +1026,9 @@ Return <code>false</code> if any of them divides the given number, else return <
<p>Returns the least common multiple of two numbers.</p> <p>Returns the least common multiple of two numbers.</p>
<p>Use the greatest common divisor (GCD) formula and <code>Math.abs()</code> to determine the least common multiple. <p>Use the greatest common divisor (GCD) formula and <code>Math.abs()</code> to determine the least common multiple.
The GCD formula uses recursion.</p> The GCD formula uses recursion.</p>
<pre><code class="language-js">const lcm = (x,y) =&gt; { <pre><code class="language-js">const lcm = (x, y) =&gt; {
const gcd = (x, y) =&gt; !y ? x : gcd(y, x % y); const gcd = (x, y) =&gt; !y ? x : gcd(y, x % y);
return Math.abs(x*y)/(gcd(x,y)); return Math.abs(x * y) / (gcd(x, y));
}; };
// lcm(12,7) -&gt; 84 // lcm(12,7) -&gt; 84
</code></pre> </code></pre>
@ -1072,13 +1071,13 @@ Then, <code>split('')</code> into individual characters, <code>reverse()</code>,
<p>Generates primes up to a given number, using the Sieve of Eratosthenes.</p> <p>Generates primes up to a given number, using the Sieve of Eratosthenes.</p>
<p>Generate an array from <code>2</code> to the given number. Use <code>Array.filter()</code> to filter out the values divisible by any number from <code>2</code> to the square root of the provided number.</p> <p>Generate an array from <code>2</code> to the given number. Use <code>Array.filter()</code> to filter out the values divisible by any number from <code>2</code> to the square root of the provided number.</p>
<pre><code class="language-js">const primes = num =&gt; { <pre><code class="language-js">const primes = num =&gt; {
let arr = Array.from({length:num-1}).map((x,i)=&gt; i+2), let arr = Array.from({length: num - 1}).map((x, i) =&gt; i + 2),
sqroot = Math.floor(Math.sqrt(num)), sqroot = Math.floor(Math.sqrt(num)),
numsTillSqroot = Array.from({length:sqroot-1}).map((x,i)=&gt; i+2); numsTillSqroot = Array.from({length: sqroot - 1}).map((x, i) =&gt; i + 2);
numsTillSqroot.forEach(x =&gt; arr = arr.filter(y =&gt; ((y%x)!==0)||(y==x))); numsTillSqroot.forEach(x =&gt; arr = arr.filter(y =&gt; ((y % x) !== 0) || (y == x)));
return arr; return arr;
} };
// primes(10) -&gt; [2,3,5,7] // primes(10) -&gt; [2,3,5,7]
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="randomintegerinrange">randomIntegerInRange</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="randomintegerinrange">randomIntegerInRange</h3></div><div class="section double-padded">
<p>Returns a random integer in the specified range.</p> <p>Returns a random integer in the specified range.</p>
@ -1096,7 +1095,7 @@ Then, <code>split('')</code> into individual characters, <code>reverse()</code>,
<p>Rounds a number to a specified amount of digits.</p> <p>Rounds a number to a specified amount of digits.</p>
<p>Use <code>Math.round()</code> and template literals to round the number to the specified number of digits. <p>Use <code>Math.round()</code> and template literals to round the number to the specified number of digits.
Omit the second argument, <code>decimals</code> to round to an integer.</p> Omit the second argument, <code>decimals</code> to round to an integer.</p>
<pre><code class="language-js">const round = (n, decimals=0) =&gt; Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); <pre><code class="language-js">const round = (n, decimals = 0) =&gt; Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
// round(1.005, 2) -&gt; 1.01 // round(1.005, 2) -&gt; 1.01
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="sdbmhashalgorithm">sdbmHashAlgorithm</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="sdbmhashalgorithm">sdbmHashAlgorithm</h3></div><div class="section double-padded">
@ -1144,7 +1143,7 @@ Use <code>window.speechSynthesis.speak()</code> to play the message.</p>
<p>Writes a JSON object to a file.</p> <p>Writes a JSON object to a file.</p>
<p>Use <code>fs.writeFile()</code>, template literals and <code>JSON.stringify()</code> to write a <code>json</code> object to a <code>.json</code> file.</p> <p>Use <code>fs.writeFile()</code>, template literals and <code>JSON.stringify()</code> to write a <code>json</code> object to a <code>.json</code> file.</p>
<pre><code class="language-js">const fs = require('fs'); <pre><code class="language-js">const fs = require('fs');
const JSONToFile = (obj, filename) =&gt; fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)) const JSONToFile = (obj, filename) =&gt; fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
// JSONToFile({test: &quot;is passed&quot;}, 'testJsonFile') -&gt; writes the object to 'testJsonFile.json' // JSONToFile({test: &quot;is passed&quot;}, 'testJsonFile') -&gt; writes the object to 'testJsonFile.json'
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="readfilelines">readFileLines</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="readfilelines">readFileLines</h3></div><div class="section double-padded">
@ -1176,9 +1175,9 @@ Also if you give it a special key (<code>childIndicator</code>) it will search d
} else if (!keysToKeep.includes(key)) { } else if (!keysToKeep.includes(key)) {
delete obj[key]; delete obj[key];
} }
 });  });
return obj; return obj;
} };
/* /*
const testObj = {a: 1, b: 2, children: {a: 1, b: 2}} const testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
cleanObj(testObj, [&quot;a&quot;],&quot;children&quot;) // { a: 1, children : { a: 1}} cleanObj(testObj, [&quot;a&quot;],&quot;children&quot;) // { a: 1, children : { a: 1}}
@ -1260,7 +1259,7 @@ Base cases are for string <code>length</code> equal to <code>2</code> or <code>1
<p>Capitalizes the first letter of a string.</p> <p>Capitalizes the first letter of a string.</p>
<p>Use destructuring and <code>toUpperCase()</code> to capitalize first letter, <code>...rest</code> to get array of characters after first letter and then <code>Array.join('')</code> to make it a string again. <p>Use destructuring and <code>toUpperCase()</code> to capitalize first letter, <code>...rest</code> to get array of characters after first letter and then <code>Array.join('')</code> to make it a string again.
Omit the <code>lowerRest</code> parameter to keep the rest of the string intact, or set it to <code>true</code> to convert to lowercase.</p> Omit the <code>lowerRest</code> parameter to keep the rest of the string intact, or set it to <code>true</code> to convert to lowercase.</p>
<pre><code class="language-js">const capitalize = ([first,...rest], lowerRest = false) =&gt; <pre><code class="language-js">const capitalize = ([first, ...rest], lowerRest = false) =&gt;
first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
// capitalize('myName') -&gt; 'MyName' // capitalize('myName') -&gt; 'MyName'
// capitalize('myName', true) -&gt; 'Myname' // capitalize('myName', true) -&gt; 'Myname'
@ -1298,9 +1297,9 @@ Omit the second argument to use a default separator of <code>_</code>.</p>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="repeatstring">repeatString</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="repeatstring">repeatString</h3></div><div class="section double-padded">
<p>Repeats a string n times using <code>String.repeat()</code></p> <p>Repeats a string n times using <code>String.repeat()</code></p>
<p>If no string is provided the default is <code>&quot;&quot;</code> and the default number of times is 2.</p> <p>If no string is provided the default is <code>&quot;&quot;</code> and the default number of times is 2.</p>
<pre><code class="language-js">const repeatString = (str=&quot;&quot;,num=2) =&gt; { <pre><code class="language-js">const repeatString = (str = '', num = 2) =&gt; {
return num &gt;= 0 ? str.repeat(num) : str; return num &gt;= 0 ? str.repeat(num) : str;
} };
// repeatString(&quot;abc&quot;,3) -&gt; 'abcabcabc' // repeatString(&quot;abc&quot;,3) -&gt; 'abcabcabc'
// repeatString(&quot;abc&quot;) -&gt; 'abcabc' // repeatString(&quot;abc&quot;) -&gt; 'abcabc'
</code></pre> </code></pre>
@ -1324,10 +1323,10 @@ Combine characters to get a string using <code>join('')</code>.</p>
For more detailed explanation of this Regex, <a href="https://regex101.com/r/bMCgAB/1">visit this Site</a>.</p> For more detailed explanation of this Regex, <a href="https://regex101.com/r/bMCgAB/1">visit this Site</a>.</p>
<pre><code class="language-js">const toCamelCase = str =&gt; { <pre><code class="language-js">const toCamelCase = str =&gt; {
let s = str &amp;&amp; str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) let s = str &amp;&amp; str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x =&gt; x.slice(0,1).toUpperCase() + x.slice(1).toLowerCase()) .map(x =&gt; x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
.join(''); .join('');
return s.slice(0,1).toLowerCase() + s.slice(1) return s.slice(0, 1).toLowerCase() + s.slice(1);
} };
// toCamelCase(&quot;some_database_field_name&quot;) -&gt; 'someDatabaseFieldName' // toCamelCase(&quot;some_database_field_name&quot;) -&gt; 'someDatabaseFieldName'
// toCamelCase(&quot;Some label that needs to be camelized&quot;) -&gt; 'someLabelThatNeedsToBeCamelized' // toCamelCase(&quot;Some label that needs to be camelized&quot;) -&gt; 'someLabelThatNeedsToBeCamelized'
// toCamelCase(&quot;some-javascript-property&quot;) -&gt; 'someJavascriptProperty' // toCamelCase(&quot;some-javascript-property&quot;) -&gt; 'someJavascriptProperty'
@ -1351,11 +1350,11 @@ For more detailed explanation of this Regex, <a href="https://regex101.com/r/bMC
<p>Converts a string to snake case.</p> <p>Converts a string to snake case.</p>
<p>Break the string into words and combine them using <code>_</code> as a separator. <p>Break the string into words and combine them using <code>_</code> as a separator.
For more detailed explanation of this Regex, <a href="https://regex101.com/r/bMCgAB/1">visit this Site</a>.</p> For more detailed explanation of this Regex, <a href="https://regex101.com/r/bMCgAB/1">visit this Site</a>.</p>
<pre><code class="language-js">const toSnakeCase = str =&gt;{ <pre><code class="language-js">const toSnakeCase = str =&gt; {
str &amp;&amp; str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) str &amp;&amp; str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x =&gt; x.toLowerCase()) .map(x =&gt; x.toLowerCase())
.join('_'); .join('_');
} };
// toSnakeCase(&quot;camelCase&quot;) -&gt; 'camel_case' // toSnakeCase(&quot;camelCase&quot;) -&gt; 'camel_case'
// toSnakeCase(&quot;some text&quot;) -&gt; 'some_text' // toSnakeCase(&quot;some text&quot;) -&gt; 'some_text'
// toSnakeCase(&quot;some-javascript-property&quot;) -&gt; 'some_javascript_property' // toSnakeCase(&quot;some-javascript-property&quot;) -&gt; 'some_javascript_property'
@ -1383,7 +1382,7 @@ Omit the second argument to use the default regex.</p>
<div class="card fluid"><div class="section double-padded"><h3 id="coalesce">coalesce</h3></div><div class="section double-padded"> <div class="card fluid"><div class="section double-padded"><h3 id="coalesce">coalesce</h3></div><div class="section double-padded">
<p>Returns the first non-null/undefined argument.</p> <p>Returns the first non-null/undefined argument.</p>
<p>Use <code>Array.find()</code> to return the first non <code>null</code>/<code>undefined</code> argument.</p> <p>Use <code>Array.find()</code> to return the first non <code>null</code>/<code>undefined</code> argument.</p>
<pre><code class="language-js">const coalesce = (...args) =&gt; args.find(_ =&gt; ![undefined, null].includes(_)) <pre><code class="language-js">const coalesce = (...args) =&gt; args.find(_ =&gt; ![undefined, null].includes(_));
// coalesce(null,undefined,&quot;&quot;,NaN, &quot;Waldo&quot;) -&gt; &quot;&quot; // coalesce(null,undefined,&quot;&quot;,NaN, &quot;Waldo&quot;) -&gt; &quot;&quot;
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="coalescefactory">coalesceFactory</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="coalescefactory">coalesceFactory</h3></div><div class="section double-padded">
@ -1398,7 +1397,7 @@ Omit the second argument to use the default regex.</p>
<p>Use <code>Array.map()</code>, <code>split()</code> and <code>Array.join()</code> to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form. <p>Use <code>Array.map()</code>, <code>split()</code> and <code>Array.join()</code> to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
<code>String.slice()</code> is used to remove <code>#</code> from string start since it's added once.</p> <code>String.slice()</code> is used to remove <code>#</code> from string start since it's added once.</p>
<pre><code class="language-js">const extendHex = shortHex =&gt; <pre><code class="language-js">const extendHex = shortHex =&gt;
'#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x =&gt; x+x).join('') '#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(x =&gt; x + x).join('');
// extendHex('#03f') -&gt; '#0033ff' // extendHex('#03f') -&gt; '#0033ff'
// extendHex('05a') -&gt; '#0055aa' // extendHex('05a') -&gt; '#0055aa'
</code></pre> </code></pre>
@ -1417,16 +1416,15 @@ Omit the second argument to use the default regex.</p>
if (h.length === 3) h = [...h].map(x =&gt; x + x).join(''); if (h.length === 3) h = [...h].map(x =&gt; x + x).join('');
else if (h.length === 8) alpha = true; else if (h.length === 8) alpha = true;
h = parseInt(h, 16); h = parseInt(h, 16);
return 'rgb' + (alpha ? 'a' : '') + '(' return 'rgb' + (alpha ? 'a' : '') + '(' +
+ (h &gt;&gt;&gt; (alpha ? 24 : 16)) + ', ' (h &gt;&gt;&gt; (alpha ? 24 : 16)) + ', ' +
+ ((h &amp; (alpha ? 0x00ff0000 : 0x00ff00)) &gt;&gt;&gt; (alpha ? 16 : 8)) + ', ' ((h &amp; (alpha ? 0x00ff0000 : 0x00ff00)) &gt;&gt;&gt; (alpha ? 16 : 8)) + ', ' +
+ ((h &amp; (alpha ? 0x0000ff00 : 0x0000ff)) &gt;&gt;&gt; (alpha ? 8 : 0)) ((h &amp; (alpha ? 0x0000ff00 : 0x0000ff)) &gt;&gt;&gt; (alpha ? 8 : 0)) +
+ (alpha ? `, ${(h &amp; 0x000000ff)}` : '') + ')'; (alpha ? `, ${(h &amp; 0x000000ff)}` : '') + ')';
}; };
// hexToRGB('#27ae60ff') -&gt; 'rgba(39, 174, 96, 255)' // hexToRGB('#27ae60ff') -&gt; 'rgba(39, 174, 96, 255)'
// hexToRGB('27ae60') -&gt; 'rgb(39, 174, 96)' // hexToRGB('27ae60') -&gt; 'rgb(39, 174, 96)'
// hexToRGB('#fff') -&gt; 'rgb(255, 255, 255)' // hexToRGB('#fff') -&gt; 'rgb(255, 255, 255)'
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isarray">isArray</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="isarray">isArray</h3></div><div class="section double-padded">
<p>Checks if the given argument is an array.</p> <p>Checks if the given argument is an array.</p>
@ -1474,10 +1472,10 @@ Omit the second argument to use the default regex.</p>
<p>Generates a random hexadecimal color code.</p> <p>Generates a random hexadecimal color code.</p>
<p>Use <code>Math.random</code> to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using <code>toString(16)</code>.</p> <p>Use <code>Math.random</code> to generate a random 24-bit(6x4bits) hexadecimal number. Use bit shifting and then convert it to an hexadecimal String using <code>toString(16)</code>.</p>
<pre><code class="language-js">const randomHexColor = () =&gt; { <pre><code class="language-js">const randomHexColor = () =&gt; {
let n = (Math.random()*0xfffff|0).toString(16); let n = (Math.random() * 0xfffff | 0).toString(16);
return '#' + (n.length !== 6 return '#' + (n.length !== 6
? (Math.random()*0xf|0).toString(16) + n : n); ? (Math.random() * 0xf | 0).toString(16) + n : n);
} };
// randomHexColorCode() -&gt; &quot;#e34155&quot; // randomHexColorCode() -&gt; &quot;#e34155&quot;
// randomHexColorCode() -&gt; &quot;#fd73a6&quot; // randomHexColorCode() -&gt; &quot;#fd73a6&quot;
// randomHexColorCode() -&gt; &quot;#4144c6&quot; // randomHexColorCode() -&gt; &quot;#4144c6&quot;
@ -1492,15 +1490,15 @@ Omit the second argument to use the default regex.</p>
<p>Measures the time taken by a function to execute.</p> <p>Measures the time taken by a function to execute.</p>
<p>Use <code>console.time()</code> and <code>console.timeEnd()</code> to measure the difference between the start and end times to determine how long the callback took to execute.</p> <p>Use <code>console.time()</code> and <code>console.timeEnd()</code> to measure the difference between the start and end times to determine how long the callback took to execute.</p>
<pre><code class="language-js">const timeTaken = callback =&gt; { <pre><code class="language-js">const timeTaken = callback =&gt; {
console.time('timeTaken'); const r = callback(); console.time('timeTaken'); const r = callback();
console.timeEnd('timeTaken'); return r; console.timeEnd('timeTaken'); return r;
}; };
// timeTaken(() =&gt; Math.pow(2, 10)) -&gt; 1024 // timeTaken(() =&gt; Math.pow(2, 10)) -&gt; 1024
// (logged): timeTaken: 0.02099609375ms // (logged): timeTaken: 0.02099609375ms
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="todecimalmark">toDecimalMark</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="todecimalmark">toDecimalMark</h3></div><div class="section double-padded">
<p>Use <code>toLocaleString()</code> to convert a float-point arithmetic to the <a href="https://en.wikipedia.org/wiki/Decimal_mark">Decimal mark</a> form. It makes a comma separated string from a number.</p> <p>Use <code>toLocaleString()</code> to convert a float-point arithmetic to the <a href="https://en.wikipedia.org/wiki/Decimal_mark">Decimal mark</a> form. It makes a comma separated string from a number.</p>
<pre><code class="language-js">const toDecimalMark = num =&gt; num.toLocaleString(&quot;en-US&quot;); <pre><code class="language-js">const toDecimalMark = num =&gt; num.toLocaleString('en-US');
// toDecimalMark(12305030388.9087) -&gt; &quot;12,305,030,388.9087&quot; // toDecimalMark(12305030388.9087) -&gt; &quot;12,305,030,388.9087&quot;
</code></pre> </code></pre>
</div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="toordinalsuffix">toOrdinalSuffix</h3></div><div class="section double-padded"> </div></div><br/><div class="card fluid"><div class="section double-padded"><h3 id="toordinalsuffix">toOrdinalSuffix</h3></div><div class="section double-padded">