From ed19d7b91cc10222a36ba92cd0401b0bef4fdda1 Mon Sep 17 00:00:00 2001 From: Travis CI Date: Thu, 28 Dec 2017 09:50:05 +0000 Subject: [PATCH] Travis build: 405 --- README.md | 700 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 700 insertions(+) diff --git a/README.md b/README.md index bc8036fca..71cd334f0 100644 --- a/README.md +++ b/README.md @@ -189,6 +189,9 @@ Use a closure to call a stored key with stored arguments. const call = (key, ...args) => context => context[key](...args); ``` +
+Examples + ```js Promise.resolve([1, 2, 3]) .then(call('map', x => 2 * x)) @@ -199,6 +202,8 @@ Promise.resolve([1, 2, 3]) .then(console.log); //[ 2, 4, 6 ] ``` +
+ [⬆ back to top](#table-of-contents) ### collectInto @@ -211,6 +216,9 @@ Given a function, return a closure that collects all inputs into an array-accept const collectInto = fn => (...args) => fn(args); ``` +
+Examples + ```js const Pall = collectInto(Promise.all.bind(Promise)); let p1 = Promise.resolve(1); @@ -219,6 +227,8 @@ let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3)); Pall(p1, p2, p3).then(console.log); ``` +
+ [⬆ back to top](#table-of-contents) ### flip @@ -231,6 +241,9 @@ Return a closure that takes variadic inputs, and splices the last argument to ma const flip = fn => (...args) => fn(args.pop(), ...args); ``` +
+Examples + ```js let a = { name: 'John Smith' }; let b = {}; @@ -241,6 +254,8 @@ b = {}; Object.assign(b, a); // == b ``` +
+ [⬆ back to top](#table-of-contents) ### pipeFunctions @@ -254,6 +269,9 @@ The first (leftmost) function can accept one or more arguments; the remaining fu const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); ``` +
+Examples + ```js const add5 = x => x + 5; const multiply = (x, y) => x * y; @@ -261,6 +279,8 @@ const multiplyAndAdd5 = pipeFunctions(multiply, add5); multiplyAndAdd5(5, 2); // 15 ``` +
+ [⬆ back to top](#table-of-contents) ### promisify @@ -279,11 +299,16 @@ const promisify = func => (...args) => ); ``` +
+Examples + ```js const delay = promisify((d, cb) => setTimeout(cb, d)); delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s ``` +
+ [⬆ back to top](#table-of-contents) ### spreadOver @@ -296,12 +321,17 @@ Use closures and the spread operator (`...`) to map the array of arguments to th const spreadOver = fn => argsArr => fn(...argsArr); ``` +
+Examples + ```js const arrayMax = spreadOver(Math.max); arrayMax([1, 2, 3]); // 3 arrayMax([1, 2, 4]); // 4 ``` +
+ [⬆ back to top](#table-of-contents) ## Array @@ -318,11 +348,16 @@ const arrayGcd = arr => { }; ``` +
+Examples + ```js arrayGcd([1, 2, 3, 4, 5]); // 1 arrayGcd([4, 8, 12]); // 4 ``` +
+ [⬆ back to top](#table-of-contents) ### arrayLcm @@ -339,11 +374,16 @@ const arrayLcm = arr => { }; ``` +
+Examples + ```js arrayLcm([1, 2, 3, 4, 5]); // 60 arrayLcm([4, 8, 12]); // 24 ``` +
+ [⬆ back to top](#table-of-contents) ### arrayMax @@ -356,10 +396,15 @@ Use `Math.max()` combined with the spread operator (`...`) to get the maximum va const arrayMax = arr => Math.max(...arr); ``` +
+Examples + ```js arrayMax([10, 1, 5]); // 10 ``` +
+ [⬆ back to top](#table-of-contents) ### arrayMin @@ -372,10 +417,15 @@ Use `Math.min()` combined with the spread operator (`...`) to get the minimum va const arrayMin = arr => Math.min(...arr); ``` +
+Examples + ```js arrayMin([10, 1, 5]); // 1 ``` +
+ [⬆ back to top](#table-of-contents) ### chunk @@ -393,10 +443,15 @@ const chunk = (arr, size) => ); ``` +
+Examples + ```js chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]] ``` +
+ [⬆ back to top](#table-of-contents) ### compact @@ -409,10 +464,15 @@ Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `u const compact = arr => arr.filter(Boolean); ``` +
+Examples + ```js compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ] ``` +
+ [⬆ back to top](#table-of-contents) ### countOccurrences @@ -425,10 +485,15 @@ Use `Array.reduce()` to increment a counter each time you encounter the specific const countOccurrences = (arr, value) => arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0); ``` +
+Examples + ```js countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3 ``` +
+ [⬆ back to top](#table-of-contents) ### deepFlatten @@ -443,10 +508,15 @@ Recursively flatten each element that is an array. const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); ``` +
+Examples + ```js deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5] ``` +
+ [⬆ back to top](#table-of-contents) ### difference @@ -462,10 +532,15 @@ const difference = (a, b) => { }; ``` +
+Examples + ```js difference([1, 2, 3], [1, 2, 4]); // [3] ``` +
+ [⬆ back to top](#table-of-contents) ### differenceWith @@ -478,10 +553,15 @@ Use `Array.filter()` and `Array.find()` to find the appropriate values. const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b))); ``` +
+Examples + ```js differenceWith([1, 1.2, 1.5, 3], [1.9, 3], (a, b) => Math.round(a) == Math.round(b)); // [1, 1.2] ``` +
+ [⬆ back to top](#table-of-contents) ### distinctValuesOfArray @@ -494,10 +574,15 @@ Use ES6 `Set` and the `...rest` operator to discard all duplicated values. const distinctValuesOfArray = arr => [...new Set(arr)]; ``` +
+Examples + ```js distinctValuesOfArray([1, 2, 2, 3, 4, 4, 5]); // [1,2,3,4,5] ``` +
+ [⬆ back to top](#table-of-contents) ### dropElements @@ -514,10 +599,15 @@ const dropElements = (arr, func) => { }; ``` +
+Examples + ```js dropElements([1, 2, 3, 4], n => n >= 3); // [3,4] ``` +
+ [⬆ back to top](#table-of-contents) ### dropRight @@ -530,12 +620,17 @@ Use `Array.slice()` to slice the remove the specified number of elements from th const dropRight = (arr, n = 1) => arr.slice(0, -n); ``` +
+Examples + ```js dropRight([1, 2, 3]); // [1,2] dropRight([1, 2, 3], 2); // [1] dropRight([1, 2, 3], 42); // [] ``` +
+ [⬆ back to top](#table-of-contents) ### everyNth @@ -548,10 +643,15 @@ Use `Array.filter()` to create a new array that contains every nth element of a const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); ``` +
+Examples + ```js everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ] ``` +
+ [⬆ back to top](#table-of-contents) ### filterNonUnique @@ -564,10 +664,15 @@ Use `Array.filter()` for an array containing only the unique values. const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); ``` +
+Examples + ```js filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5] ``` +
+ [⬆ back to top](#table-of-contents) ### flatten @@ -580,10 +685,15 @@ Use a new array and concatenate it with the spread input array causing a shallow const flatten = arr => [].concat(...arr); ``` +
+Examples + ```js flatten([1, [2], 3, 4]); // [1,2,3,4] ``` +
+ [⬆ back to top](#table-of-contents) ### flattenDepth @@ -602,10 +712,15 @@ const flattenDepth = (arr, depth = 1) => : arr.reduce((a, v) => a.concat(v), []); ``` +
+Examples + ```js flattenDepth([1, [2], 3, 4]); // [1,2,3,4] ``` +
+ [⬆ back to top](#table-of-contents) ### groupBy @@ -623,11 +738,16 @@ const groupBy = (arr, func) => }, {}); ``` +
+Examples + ```js groupBy([6.1, 4.2, 6.3], Math.floor); // {4: [4.2], 6: [6.1, 6.3]} groupBy(['one', 'two', 'three'], 'length'); // {3: ['one', 'two'], 5: ['three']} ``` +
+ [⬆ back to top](#table-of-contents) ### head @@ -640,10 +760,15 @@ Use `arr[0]` to return the first element of the passed array. const head = arr => arr[0]; ``` +
+Examples + ```js head([1, 2, 3]); // 1 ``` +
+ [⬆ back to top](#table-of-contents) ### initial @@ -656,10 +781,15 @@ Use `arr.slice(0,-1)` to return all but the last element of the array. const initial = arr => arr.slice(0, -1); ``` +
+Examples + ```js initial([1, 2, 3]); // [1,2] ``` +
+ [⬆ back to top](#table-of-contents) ### initialize2DArray @@ -675,10 +805,15 @@ const initialize2DArray = (w, h, val = null) => .map(() => Array(w).fill(val)); ``` +
+Examples + ```js initialize2DArray(2, 2, 0); // [[0,0], [0,0]] ``` +
+ [⬆ back to top](#table-of-contents) ### initializeArrayWithRange @@ -693,11 +828,16 @@ const initializeArrayWithRange = (end, start = 0) => Array.from({ length: end + 1 - start }).map((v, i) => i + start); ``` +
+Examples + ```js initializeArrayWithRange(5); // [0,1,2,3,4,5] initializeArrayWithRange(7, 3); // [3,4,5,6,7] ``` +
+ [⬆ back to top](#table-of-contents) ### initializeArrayWithValues @@ -711,10 +851,15 @@ You can omit `value` to use a default value of `0`. const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value); ``` +
+Examples + ```js initializeArrayWithValues(5, 2); // [2,2,2,2,2] ``` +
+ [⬆ back to top](#table-of-contents) ### intersection @@ -730,10 +875,15 @@ const intersection = (a, b) => { }; ``` +
+Examples + ```js intersection([1, 2, 3], [4, 3, 2]); // [2,3] ``` +
+ [⬆ back to top](#table-of-contents) ### last @@ -746,10 +896,15 @@ Use `arr.length - 1` to compute the index of the last element of the given array const last = arr => arr[arr.length - 1]; ``` +
+Examples + ```js last([1, 2, 3]); // 3 ``` +
+ [⬆ back to top](#table-of-contents) ### mapObject @@ -765,11 +920,16 @@ const mapObject = (arr, fn) => ))(); ``` +
+Examples + ```js const squareIt = arr => mapObject(arr, a => a * a); squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 } ``` +
+ [⬆ back to top](#table-of-contents) ### nthElement @@ -784,11 +944,16 @@ 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]; ``` +
+Examples + ```js nthElement(['a', 'b', 'c'], 1); // 'b' nthElement(['a', 'b', 'b'], -3); // 'a' ``` +
+ [⬆ back to top](#table-of-contents) ### pick @@ -802,10 +967,15 @@ const pick = (obj, arr) => arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); ``` +
+Examples + ```js pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 } ``` +
+ [⬆ back to top](#table-of-contents) ### pull @@ -826,6 +996,9 @@ const pull = (arr, ...args) => { }; ``` +
+Examples + ```js let myArray1 = ['a', 'b', 'c', 'a', 'b', 'c']; pull(myArray1, 'a', 'c'); @@ -836,6 +1009,8 @@ pull(myArray2, ['a', 'c']); console.log(myArray2); // [ 'b', 'b' ] ``` +
+ [⬆ back to top](#table-of-contents) ### pullAtIndex @@ -858,6 +1033,9 @@ const pullAtIndex = (arr, pullArr) => { }; ``` +
+Examples + ```js let myArray = ['a', 'b', 'c', 'd']; let pulled = pullAtIndex(myArray, [1, 3]); @@ -866,6 +1044,8 @@ console.log(myArray); // [ 'a', 'c' ] console.log(pulled); // [ 'b', 'd' ] ``` +
+ [⬆ back to top](#table-of-contents) ### pullAtValue @@ -887,6 +1067,9 @@ const pullAtValue = (arr, pullArr) => { }; ``` +
+Examples + ```js let myArray = ['a', 'b', 'c', 'd']; let pulled = pullAtValue(myArray, ['b', 'd']); @@ -894,6 +1077,8 @@ console.log(myArray); // [ 'a', 'c' ] console.log(pulled); // [ 'b', 'd' ] ``` +
+ [⬆ back to top](#table-of-contents) ### remove @@ -913,10 +1098,15 @@ const remove = (arr, func) => : []; ``` +
+Examples + ```js remove([1, 2, 3, 4], n => n % 2 == 0); // [2, 4] ``` +
+ [⬆ back to top](#table-of-contents) ### sample @@ -930,10 +1120,15 @@ This method also works with strings. const sample = arr => arr[Math.floor(Math.random() * arr.length)]; ``` +
+Examples + ```js sample([3, 7, 9, 11]); // 9 ``` +
+ [⬆ back to top](#table-of-contents) ### shuffle @@ -953,12 +1148,17 @@ const shuffle = ([...arr]) => { }; ``` +
+Examples + ```js const foo = [1, 2, 3]; shuffle(foo); // [2,3,1] console.log(foo); // [1,2,3] ``` +
+ [⬆ back to top](#table-of-contents) ### similarity @@ -971,10 +1171,15 @@ Use `filter()` to remove values that are not part of `values`, determined using const similarity = (arr, values) => arr.filter(v => values.includes(v)); ``` +
+Examples + ```js similarity([1, 2, 3], [1, 2, 4]); // [1,2] ``` +
+ [⬆ back to top](#table-of-contents) ### symmetricDifference @@ -991,10 +1196,15 @@ const symmetricDifference = (a, b) => { }; ``` +
+Examples + ```js symmetricDifference([1, 2, 3], [1, 2, 4]); // [3,4] ``` +
+ [⬆ back to top](#table-of-contents) ### tail @@ -1007,11 +1217,16 @@ Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise, retur const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); ``` +
+Examples + ```js tail([1, 2, 3]); // [2,3] tail([1]); // [1] ``` +
+ [⬆ back to top](#table-of-contents) ### take @@ -1024,11 +1239,16 @@ Use `Array.slice()` to create a slice of the array with `n` elements taken from const take = (arr, n = 1) => arr.slice(0, n); ``` +
+Examples + ```js take([1, 2, 3], 5); // [1, 2, 3] take([1, 2, 3], 0); // [] ``` +
+ [⬆ back to top](#table-of-contents) ### takeRight @@ -1041,11 +1261,16 @@ Use `Array.slice()` to create a slice of the array with `n` elements taken from const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); ``` +
+Examples + ```js takeRight([1, 2, 3], 2); // [ 2, 3 ] takeRight([1, 2, 3]); // [3] ``` +
+ [⬆ back to top](#table-of-contents) ### union @@ -1058,10 +1283,15 @@ Create a `Set` with all values of `a` and `b` and convert to an array. const union = (a, b) => Array.from(new Set([...a, ...b])); ``` +
+Examples + ```js union([1, 2, 3], [4, 3, 2]); // [1,2,3,4] ``` +
+ [⬆ back to top](#table-of-contents) ### without @@ -1076,10 +1306,15 @@ _(For a snippet that mutates the original array see [`pull`](#pull))_ const without = (arr, ...args) => arr.filter(v => !args.includes(v)); ``` +
+Examples + ```js without([2, 1, 2, 3], 1, 2); // [3] ``` +
+ [⬆ back to top](#table-of-contents) ### zip @@ -1099,11 +1334,16 @@ const zip = (...arrays) => { }; ``` +
+Examples + ```js 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]] ``` +
+ [⬆ back to top](#table-of-contents) ### zipObject @@ -1117,11 +1357,16 @@ const zipObject = (props, values) => props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {}); ``` +
+Examples + ```js zipObject(['a', 'b', 'c'], [1, 2]); // {a: 1, b: 2, c: undefined} zipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2} ``` +
+ [⬆ back to top](#table-of-contents) ## Browser @@ -1136,10 +1381,15 @@ const arrayToHtmlList = (arr, listID) => arr.map(item => (document.querySelector('#' + listID).innerHTML += `
  • ${item}
  • `)); ``` +
    +Examples + ```js arrayToHtmlList(['item 1', 'item 2'], 'myListID'); ``` +
    + [⬆ back to top](#table-of-contents) ### bottomVisible @@ -1154,10 +1404,15 @@ const bottomVisible = () => (document.documentElement.scrollHeight || document.documentElement.clientHeight); ``` +
    +Examples + ```js bottomVisible(); // true ``` +
    + [⬆ back to top](#table-of-contents) ### currentURL @@ -1170,10 +1425,15 @@ Use `window.location.href` to get current URL. const currentURL = () => window.location.href; ``` +
    +Examples + ```js currentURL(); // 'https://google.com' ``` +
    + [⬆ back to top](#table-of-contents) ### detectDeviceType @@ -1189,11 +1449,16 @@ const detectDeviceType = () => : 'Desktop'; ``` +
    +Examples + ```js detectDeviceType(); // "Mobile" detectDeviceType(); // "Desktop" ``` +
    + [⬆ back to top](#table-of-contents) ### elementIsVisibleInViewport @@ -1216,12 +1481,17 @@ const elementIsVisibleInViewport = (el, partiallyVisible = false) => { }; ``` +
    +Examples + ```js // e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10} elementIsVisibleInViewport(el); // false // (not fully visible) elementIsVisibleInViewport(el, true); // true // (partially visible) ``` +
    + [⬆ back to top](#table-of-contents) ### getScrollPosition @@ -1238,10 +1508,15 @@ const getScrollPosition = (el = window) => ({ }); ``` +
    +Examples + ```js getScrollPosition(); // {x: 0, y: 200} ``` +
    + [⬆ back to top](#table-of-contents) ### getURLParameters @@ -1258,10 +1533,15 @@ const getURLParameters = url => .reduce((a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), {}); ``` +
    +Examples + ```js getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'} ``` +
    + [⬆ back to top](#table-of-contents) ### httpsRedirect @@ -1270,12 +1550,17 @@ Redirects the page to HTTPS if its currently in HTTP. Also, pressing the back bu Use `location.protocol` to get the protocol currently being used. If it's not HTTPS, use `location.replace()` to replace the existing page with the HTTPS version of the page. Use `location.href` to get the full address, split it with `String.split()` and remove the protocol part of the URL. +
    +Examples + ```js const httpsRedirect = () => { if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); }; ``` +
    + [⬆ back to top](#table-of-contents) ### redirect @@ -1290,10 +1575,15 @@ const redirect = (url, asLink = true) => asLink ? (window.location.href = url) : window.location.replace(url); ``` +
    +Examples + ```js redirect('https://google.com'); ``` +
    + [⬆ back to top](#table-of-contents) ### scrollToTop @@ -1313,10 +1603,15 @@ const scrollToTop = () => { }; ``` +
    +Examples + ```js scrollToTop(); ``` +
    + [⬆ back to top](#table-of-contents) ## Date @@ -1331,10 +1626,15 @@ const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); ``` +
    +Examples + ```js getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9 ``` +
    + [⬆ back to top](#table-of-contents) ### JSONToDate @@ -1350,10 +1650,15 @@ const JSONToDate = arr => { }; ``` +
    +Examples + ```js JSONToDate(/Date(1489525200000)/); // "14/3/2017" ``` +
    + [⬆ back to top](#table-of-contents) ### toEnglishDate @@ -1374,10 +1679,15 @@ const toEnglishDate = time => { }; ``` +
    +Examples + ```js toEnglishDate('09/21/2010'); // '21/09/2010' ``` +
    + [⬆ back to top](#table-of-contents) ### tomorrow @@ -1389,10 +1699,15 @@ Use `new Date()` to get today's date, adding `86400000` of seconds to it(24 hour const tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0]; ``` +
    +Examples + ```js tomorrow(); // 2017-12-27 (if current date is 2017-12-26) ``` +
    + [⬆ back to top](#table-of-contents) ## Function @@ -1410,6 +1725,9 @@ const chainAsync = fns => { }; ``` +
    +Examples + ```js chainAsync([ next => { @@ -1426,6 +1744,8 @@ chainAsync([ ]); ``` +
    + [⬆ back to top](#table-of-contents) ### compose @@ -1439,6 +1759,9 @@ The last (rightmost) function can accept one or more arguments; the remaining fu const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); ``` +
    +Examples + ```js const add5 = x => x + 5; const multiply = (x, y) => x * y; @@ -1446,6 +1769,8 @@ const multiplyAndAdd5 = compose(add5, multiply); multiplyAndAdd5(5, 2); // 15 ``` +
    + [⬆ back to top](#table-of-contents) ### curry @@ -1462,11 +1787,16 @@ const curry = (fn, arity = fn.length, ...args) => arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args); ``` +
    +Examples + ```js curry(Math.pow)(2)(10); // 1024 curry(Math.min, 3)(10)(50)(2); // 2 ``` +
    + [⬆ back to top](#table-of-contents) ### functionName @@ -1479,10 +1809,15 @@ Use `console.debug()` and the `name` property of the passed method to log the me const functionName = fn => (console.debug(fn.name), fn); ``` +
    +Examples + ```js functionName(Math.max); // max (logged in debug channel of console) ``` +
    + [⬆ back to top](#table-of-contents) ### runPromisesInSeries @@ -1495,11 +1830,16 @@ Use `Array.reduce()` to create a promise chain, where each promise returns the n const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); ``` +
    +Examples + ```js const delay = d => new Promise(r => setTimeout(r, d)); runPromisesInSeries([() => delay(1000), () => delay(2000)]); // //executes each promise sequentially, taking a total of 3 seconds to complete ``` +
    + [⬆ back to top](#table-of-contents) ### sleep @@ -1512,6 +1852,9 @@ Delay executing part of an `async` function, by putting it to sleep, returning a const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); ``` +
    +Examples + ```js async function sleepyWork() { console.log("I'm going to sleep for 1 second."); @@ -1520,6 +1863,8 @@ async function sleepyWork() { } ``` +
    + [⬆ back to top](#table-of-contents) ## Logic @@ -1533,11 +1878,16 @@ Take a predicate function and apply `not` to it with its arguments. const negate = func => (...args) => !func(...args); ``` +
    +Examples + ```js filter([1, 2, 3, 4, 5, 6], negate(isEven)); // [1, 3, 5] negate(isOdd)(1); // false ``` +
    + [⬆ back to top](#table-of-contents) ## Math @@ -1551,10 +1901,15 @@ Use `Array.reduce()` to add each value to an accumulator, initialized with a val const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length; ``` +
    +Examples + ```js arrayAverage([1, 2, 3]); // 2 ``` +
    + [⬆ back to top](#table-of-contents) ### arraySum @@ -1567,10 +1922,15 @@ Use `Array.reduce()` to add each value to an accumulator, initialized with a val const arraySum = arr => arr.reduce((acc, val) => acc + val, 0); ``` +
    +Examples + ```js arraySum([1, 2, 3, 4]); // 10 ``` +
    + [⬆ back to top](#table-of-contents) ### clampNumber @@ -1584,12 +1944,17 @@ Otherwise, return the nearest number in the range. const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); ``` +
    +Examples + ```js clampNumber(2, 3, 5); // 3 clampNumber(1, -1, -5); // -1 clampNumber(3, 2, 4); // 3 ``` +
    + [⬆ back to top](#table-of-contents) ### collatz @@ -1602,11 +1967,16 @@ If `n` is even, return `n/2`. Otherwise, return `3n+1`. const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1); ``` +
    +Examples + ```js collatz(8); // 4 collatz(5); // 16 ``` +
    + [⬆ back to top](#table-of-contents) ### digitize @@ -1620,10 +1990,15 @@ Use `Array.map()` and `parseInt()` to transform each value to an integer. const digitize = n => [...('' + n)].map(i => parseInt(i)); ``` +
    +Examples + ```js digitize(123); // [1, 2, 3] ``` +
    + [⬆ back to top](#table-of-contents) ### distance @@ -1636,10 +2011,15 @@ Use `Math.hypot()` to calculate the Euclidean distance between two points. const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); ``` +
    +Examples + ```js distance(1, 1, 2, 3); // 2.23606797749979 ``` +
    + [⬆ back to top](#table-of-contents) ### factorial @@ -1660,10 +2040,15 @@ const factorial = n => : n <= 1 ? 1 : n * factorial(n - 1); ``` +
    +Examples + ```js factorial(6); // 720 ``` +
    + [⬆ back to top](#table-of-contents) ### fibonacci @@ -1681,10 +2066,15 @@ const fibonacci = n => ); ``` +
    +Examples + ```js fibonacci(6); // 720 ``` +
    + [⬆ back to top](#table-of-contents) ### fibonacciCountUntilNum @@ -1698,10 +2088,15 @@ const fibonacciCountUntilNum = num => Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); ``` +
    +Examples + ```js fibonacciCountUntilNum(10); // 7 ``` +
    + [⬆ back to top](#table-of-contents) ### fibonacciUntilNum @@ -1722,10 +2117,15 @@ const fibonacciUntilNum = num => { }; ``` +
    +Examples + ```js fibonacciCountUntilNum(10); // 7 ``` +
    + [⬆ back to top](#table-of-contents) ### gcd @@ -1740,10 +2140,15 @@ Otherwise, return the GCD of `y` and the remainder of the division `x/y`. const gcd = (x, y) => (!y ? x : gcd(y, x % y)); ``` +
    +Examples + ```js gcd(8, 36); // 4 ``` +
    + [⬆ back to top](#table-of-contents) ### hammingDistance @@ -1757,10 +2162,15 @@ Count and return the number of `1`s in the string, using `match(/1/g)`. const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length; ``` +
    +Examples + ```js hammingDistance(2, 3); // 1 ``` +
    + [⬆ back to top](#table-of-contents) ### inRange @@ -1777,6 +2187,9 @@ const inRange = (n, start, end = null) => { }; ``` +
    +Examples + ```js inRange(3, 2, 5); // true inRange(3, 4); // true @@ -1784,6 +2197,8 @@ inRange(2, 3, 5); // false inrange(3, 2); // false ``` +
    + [⬆ back to top](#table-of-contents) ### isArmstrongNumber @@ -1799,12 +2214,17 @@ const isArmstrongNumber = digits => ); ``` +
    +Examples + ```js isArmstrongNumber(1634); // true isArmstrongNumber(371); // true isArmstrongNumber(56); // false ``` +
    + [⬆ back to top](#table-of-contents) ### isDivisible @@ -1817,10 +2237,15 @@ Use the modulo operator (`%`) to check if the remainder is equal to `0`. const isDivisible = (dividend, divisor) => dividend % divisor === 0; ``` +
    +Examples + ```js isDivisible(6, 3); // true ``` +
    + [⬆ back to top](#table-of-contents) ### isEven @@ -1834,10 +2259,15 @@ Returns `true` if the number is even, `false` if the number is odd. const isEven = num => num % 2 === 0; ``` +
    +Examples + ```js isEven(3); // false ``` +
    + [⬆ back to top](#table-of-contents) ### isPrime @@ -1855,11 +2285,16 @@ const isPrime = num => { }; ``` +
    +Examples + ```js isPrime(11); // true isPrime(12); // false ``` +
    + [⬆ back to top](#table-of-contents) ### lcm @@ -1876,10 +2311,15 @@ const lcm = (x, y) => { }; ``` +
    +Examples + ```js lcm(12, 7); // 84 ``` +
    + [⬆ back to top](#table-of-contents) ### median @@ -1897,11 +2337,16 @@ const median = arr => { }; ``` +
    +Examples + ```js median([5, 6, 50, 1, -5]); // 5 median([0, 10, -2, 7]); // 3.5 ``` +
    + [⬆ back to top](#table-of-contents) ### palindrome @@ -1924,10 +2369,15 @@ const palindrome = str => { }; ``` +
    +Examples + ```js palindrome('taco cat'); // true ``` +
    + [⬆ back to top](#table-of-contents) ### percentile @@ -1941,10 +2391,15 @@ const percentile = (arr, val) => 100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length; ``` +
    +Examples + ```js percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6); // 55 ``` +
    + [⬆ back to top](#table-of-contents) ### powerset @@ -1957,10 +2412,15 @@ Use `Array.reduce()` combined with `Array.map()` to iterate over elements and co const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); ``` +
    +Examples + ```js powerset([1, 2]); // [[], [1], [2], [2,1]] ``` +
    + [⬆ back to top](#table-of-contents) ### primes @@ -1979,10 +2439,15 @@ const primes = num => { }; ``` +
    +Examples + ```js primes(10); // [2,3,5,7] ``` +
    + [⬆ back to top](#table-of-contents) ### randomIntegerInRange @@ -1995,10 +2460,15 @@ Use `Math.random()` to generate a random number and map it to the desired range, const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; ``` +
    +Examples + ```js randomIntegerInRange(0, 5); // 2 ``` +
    + [⬆ back to top](#table-of-contents) ### randomNumberInRange @@ -2011,10 +2481,15 @@ Use `Math.random()` to generate a random value, map it to the desired range usin const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; ``` +
    +Examples + ```js randomNumberInRange(2, 10); // 6.0211363285087005 ``` +
    + [⬆ back to top](#table-of-contents) ### round @@ -2028,10 +2503,15 @@ Omit the second argument, `decimals` to round to an integer. const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); ``` +
    +Examples + ```js round(1.005, 2); // 1.01 ``` +
    + [⬆ back to top](#table-of-contents) ### standardDeviation @@ -2054,11 +2534,16 @@ const standardDeviation = (arr, usePopulation = false) => { }; ``` +
    +Examples + ```js standardDeviation([10, 2, 38, 23, 38, 23, 21]); // 13.284434142114991 (sample) standardDeviation([10, 2, 38, 23, 38, 23, 21], true); // 12.29899614287479 (population) ``` +
    + [⬆ back to top](#table-of-contents) ## Media @@ -2079,10 +2564,15 @@ const speechSynthesis = message => { }; ``` +
    +Examples + ```js speechSynthesis('Hello, World'); // // plays the message ``` +
    + [⬆ back to top](#table-of-contents) ## Node @@ -2098,10 +2588,15 @@ const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); ``` +
    +Examples + ```js JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json' ``` +
    + [⬆ back to top](#table-of-contents) ### readFileLines @@ -2121,6 +2616,9 @@ const readFileLines = filename => .split('\n'); ``` +
    +Examples + ```js /* contents of test.txt : @@ -2134,6 +2632,8 @@ console.log(arr); // ['line1', 'line2', 'line3'] ``` +
    + [⬆ back to top](#table-of-contents) ## Object @@ -2157,11 +2657,16 @@ const cleanObj = (obj, keysToKeep = [], childIndicator) => { }; ``` +
    +Examples + ```js const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } }; cleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}} ``` +
    + [⬆ back to top](#table-of-contents) ### objectFromPairs @@ -2174,10 +2679,15 @@ Use `Array.reduce()` to create and combine key-value pairs. const objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {}); ``` +
    +Examples + ```js objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2} ``` +
    + [⬆ back to top](#table-of-contents) ### objectToPairs @@ -2190,10 +2700,15 @@ Use `Object.keys()` and `Array.map()` to iterate over the object's keys and prod const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); ``` +
    +Examples + ```js objectToPairs({ a: 1, b: 2 }); // [['a',1],['b',2]]) ``` +
    + [⬆ back to top](#table-of-contents) ### orderBy @@ -2216,6 +2731,9 @@ const orderBy = (arr, props, orders) => ); ``` +
    +Examples + ```js const users = [ { name: 'fred', age: 48 }, @@ -2227,6 +2745,8 @@ orderBy(users, ['name', 'age'], ['asc', 'desc']); // [{name: 'barney', age: 36}, orderBy(users, ['name', 'age']); // [{name: 'barney', age: 34}, {name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}] ``` +
    + [⬆ back to top](#table-of-contents) ### select @@ -2240,11 +2760,16 @@ const select = (from, selector) => selector.split('.').reduce((prev, cur) => prev && prev[cur], from); ``` +
    +Examples + ```js const obj = { selector: { to: { val: 'val to select' } } }; select(obj, 'selector.to.val'); // 'val to select' ``` +
    + [⬆ back to top](#table-of-contents) ### shallowClone @@ -2257,12 +2782,17 @@ Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of th const shallowClone = obj => Object.assign({}, obj); ``` +
    +Examples + ```js const a = { x: true, y: 1 }; const b = shallowClone(a); a === b; // false ``` +
    + [⬆ back to top](#table-of-contents) ### truthCheckCollection @@ -2275,10 +2805,15 @@ Use `Array.every()` to check if each passed object has the specified property an const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]); ``` +
    +Examples + ```js truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true ``` +
    + [⬆ back to top](#table-of-contents) ## String @@ -2304,10 +2839,15 @@ const anagrams = str => { }; ``` +
    +Examples + ```js anagrams('abc'); // ['abc','acb','bac','bca','cab','cba'] ``` +
    + [⬆ back to top](#table-of-contents) ### Capitalize @@ -2322,11 +2862,16 @@ const capitalize = ([first, ...rest], lowerRest = false) => first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); ``` +
    +Examples + ```js capitalize('fooBar'); // 'FooBar' capitalize('fooBar', true); // 'Foobar' ``` +
    + [⬆ back to top](#table-of-contents) ### capitalizeEveryWord @@ -2339,10 +2884,15 @@ Use `replace()` to match the first character of each word and `toUpperCase()` to const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); ``` +
    +Examples + ```js capitalizeEveryWord('hello world!'); // 'Hello World!' ``` +
    + [⬆ back to top](#table-of-contents) ### countVowels @@ -2355,11 +2905,16 @@ Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a `s const countVowels = str => (str.match(/[aeiou]/gi) || []).length; ``` +
    +Examples + ```js countVowels('foobar'); // 3 countVowels('gym'); // 0 ``` +
    + [⬆ back to top](#table-of-contents) ### escapeRegExp @@ -2372,10 +2927,15 @@ Use `replace()` to escape special characters. const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); ``` +
    +Examples + ```js escapeRegExp('(test)'); // \\(test\\) ``` +
    + [⬆ back to top](#table-of-contents) ### fromCamelCase @@ -2393,12 +2953,17 @@ const fromCamelCase = (str, separator = '_') => .toLowerCase(); ``` +
    +Examples + ```js fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name' fromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized' fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property' ``` +
    + [⬆ back to top](#table-of-contents) ### repeatString @@ -2413,11 +2978,16 @@ const repeatString = (str = '', num = 2) => { }; ``` +
    +Examples + ```js repeatString('abc', 3); // 'abcabcabc' repeatString('abc'); // 'abcabc' ``` +
    + [⬆ back to top](#table-of-contents) ### reverseString @@ -2435,10 +3005,15 @@ const reverseString = str => .join(''); ``` +
    +Examples + ```js reverseString('foobar'); // 'raboof' ``` +
    + [⬆ back to top](#table-of-contents) ### sortCharactersInString @@ -2455,10 +3030,15 @@ const sortCharactersInString = str => .join(''); ``` +
    +Examples + ```js sortCharactersInString('cabbage'); // 'aabbceg' ``` +
    + [⬆ back to top](#table-of-contents) ### toCamelCase @@ -2480,6 +3060,9 @@ const toCamelCase = str => { }; ``` +
    +Examples + ```js toCamelCase('some_database_field_name'); // 'someDatabaseFieldName' toCamelCase('Some label that needs to be camelized'); // 'someLabelThatNeedsToBeCamelized' @@ -2487,6 +3070,8 @@ toCamelCase('some-javascript-property'); // 'someJavascriptProperty' toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'someMixedStringWithSpacesUnderscoresAndHyphens' ``` +
    + [⬆ back to top](#table-of-contents) ### toKebabCase @@ -2505,6 +3090,9 @@ const toKebabCase = str => .join('-'); ``` +
    +Examples + ```js toKebabCase('camelCase'); // 'camel-case' toKebabCase('some text'); // 'some-text' @@ -2513,6 +3101,8 @@ toKebabCase('AllThe-small Things'); // "all-the-small-things" toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // "i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html" ``` +
    + [⬆ back to top](#table-of-contents) ### toSnakeCase @@ -2532,6 +3122,9 @@ const toSnakeCase = str => { }; ``` +
    +Examples + ```js toSnakeCase('camelCase'); // 'camel_case' toSnakeCase('some text'); // 'some_text' @@ -2541,6 +3134,8 @@ toSnakeCase('AllThe-small Things'); // "all_the_smal_things" toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // "i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html" ``` +
    + [⬆ back to top](#table-of-contents) ### truncateString @@ -2555,10 +3150,15 @@ const truncateString = (str, num) => str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; ``` +
    +Examples + ```js truncateString('boomerang', 7); // 'boom...' ``` +
    + [⬆ back to top](#table-of-contents) ### words @@ -2572,11 +3172,16 @@ Omit the second argument to use the default regex. const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); ``` +
    +Examples + ```js words('I love javaScript!!'); // ["I", "love", "javaScript"] words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"] ``` +
    + [⬆ back to top](#table-of-contents) ## Utility @@ -2590,10 +3195,15 @@ Use `Array.find()` to return the first non `null`/`undefined` argument. const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); ``` +
    +Examples + ```js coalesce(null, undefined, '', NaN, 'Waldo'); // "" ``` +
    + [⬆ back to top](#table-of-contents) ### coalesceFactory @@ -2606,11 +3216,16 @@ Use `Array.find()` to return the first argument that returns `true` from the pro const coalesceFactory = valid => (...args) => args.find(valid); ``` +
    +Examples + ```js const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_)); customCoalesce(undefined, null, NaN, '', 'Waldo'); // "Waldo" ``` +
    + [⬆ back to top](#table-of-contents) ### extendHex @@ -2629,11 +3244,16 @@ const extendHex = shortHex => .join(''); ``` +
    +Examples + ```js extendHex('#03f'); // '#0033ff' extendHex('05a'); // '#0055aa' ``` +
    + [⬆ back to top](#table-of-contents) ### getType @@ -2647,10 +3267,15 @@ const getType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase(); ``` +
    +Examples + ```js getType(new Set([1, 2, 3])); // "set" ``` +
    + [⬆ back to top](#table-of-contents) ### hexToRGB @@ -2681,12 +3306,17 @@ const hexToRGB = hex => { }; ``` +
    +Examples + ```js hexToRGB('#27ae60ff'); // 'rgba(39, 174, 96, 255)' hexToRGB('27ae60'); // 'rgb(39, 174, 96)' hexToRGB('#fff'); // 'rgb(255, 255, 255)' ``` +
    + [⬆ back to top](#table-of-contents) ### isArray @@ -2699,11 +3329,16 @@ Use `Array.isArray()` to check if a value is classified as an array. const isArray = val => !!val && Array.isArray(val); ``` +
    +Examples + ```js isArray(null); // false isArray([1]); // true ``` +
    + [⬆ back to top](#table-of-contents) ### isBoolean @@ -2716,11 +3351,16 @@ Use `typeof` to check if a value is classified as a boolean primitive. const isBoolean = val => typeof val === 'boolean'; ``` +
    +Examples + ```js isBoolean(null); // false isBoolean(false); // true ``` +
    + [⬆ back to top](#table-of-contents) ### isFunction @@ -2733,11 +3373,16 @@ Use `typeof` to check if a value is classified as a function primitive. const isFunction = val => val && typeof val === 'function'; ``` +
    +Examples + ```js isFunction('x'); // false isFunction(x => x); // true ``` +
    + [⬆ back to top](#table-of-contents) ### isNumber @@ -2750,10 +3395,15 @@ Use `typeof` to check if a value is classified as a number primitive. const isNumber = val => typeof val === 'number'; ``` +
    +Examples + ```js isNumber('1'); // false isNumber(1); // true ``` +
    + [⬆ back to top](#table-of-contents) ### isString @@ -2766,11 +3416,16 @@ Use `typeof` to check if a value is classified as a string primitive. const isString = val => typeof val === 'string'; ``` +
    +Examples + ```js isString(10); // false isString('10'); // true ``` +
    + [⬆ back to top](#table-of-contents) ### isSymbol @@ -2783,11 +3438,16 @@ Use `typeof` to check if a value is classified as a symbol primitive. const isSymbol = val => typeof val === 'symbol'; ``` +
    +Examples + ```js isSymbol('x'); // false isSymbol(Symbol('x')); // true ``` +
    + [⬆ back to top](#table-of-contents) ### randomHexColorCode @@ -2803,12 +3463,17 @@ const randomHexColorCode = () => { }; ``` +
    +Examples + ```js randomHexColorCode(); // "#e34155" randomHexColorCode(); // "#fd73a6" randomHexColorCode(); // "#4144c6" ``` +
    + [⬆ back to top](#table-of-contents) ### RGBToHex @@ -2821,10 +3486,15 @@ Convert given RGB parameters to hexadecimal string using bitwise left-shift oper const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); ``` +
    +Examples + ```js RGBToHex(255, 165, 1); // 'ffa501' ``` +
    + [⬆ back to top](#table-of-contents) ### sbdm @@ -2844,11 +3514,16 @@ const sdbm = str => { }; ``` +
    +Examples + ```js console.log(sdbm('name')); // -3521204949 console.log(sdbm('age')); // 808122783 ``` +
    + [⬆ back to top](#table-of-contents) ### timeTaken @@ -2866,11 +3541,16 @@ const timeTaken = callback => { }; ``` +
    +Examples + ```js timeTaken(() => Math.pow(2, 10)); // 1024 // (logged): timeTaken: 0.02099609375ms ``` +
    + [⬆ back to top](#table-of-contents) ### toDecimalMark @@ -2881,10 +3561,15 @@ Use `toLocaleString()` to convert a float-point arithmetic to the [Decimal mark] const toDecimalMark = num => num.toLocaleString('en-US'); ``` +
    +Examples + ```js toDecimalMark(12305030388.9087); // "12,305,030,388.9087" ``` +
    + [⬆ back to top](#table-of-contents) ### toOrdinalSuffix @@ -2908,10 +3593,15 @@ const toOrdinalSuffix = num => { }; ``` +
    +Examples + ```js toOrdinalSuffix('123'); // "123rd" ``` +
    + [⬆ back to top](#table-of-contents) ### UUIDGenerator @@ -2927,10 +3617,15 @@ const UUIDGenerator = () => ); ``` +
    +Examples + ```js UUIDGenerator(); // '7982fcfe-5721-4632-bede-6000885be57d' ``` +
    + [⬆ back to top](#table-of-contents) ### validateNumber @@ -2945,10 +3640,15 @@ Use `Number()` to check if the coercion holds. const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; ``` +
    +Examples + ```js validateNumber('10'); // true ``` +
    + [⬆ back to top](#table-of-contents) ## Credits