From 5727cb4ff059e4efd9ba6a04892a2b2bc671078b Mon Sep 17 00:00:00 2001 From: Felix Wu Date: Fri, 14 Sep 2018 15:15:41 +0200 Subject: [PATCH] build --- README.md | 4414 +++++++++++++++++------------------- package-lock.json | 6 +- package.json | 2 +- snippets_archive/README.md | 56 +- 4 files changed, 2070 insertions(+), 2408 deletions(-) diff --git a/README.md b/README.md index b13302e49..cd61099f9 100644 --- a/README.md +++ b/README.md @@ -81,12 +81,12 @@ average(1, 2, 3); ## Table of Contents -### πŸ”Œ Adapter +### πŸ”Œ Adapter
-View contents - -* [`ary`](#ary) + View contents + + * [`ary`](#ary) * [`call`](#call) * [`collectInto`](#collectinto) * [`flip`](#flip) @@ -100,13 +100,13 @@ average(1, 2, 3); * [`unary`](#unary)
- -### πŸ“š Array + +### πŸ“š Array
-View contents - -* [`all`](#all) + View contents + + * [`all`](#all) * [`allEqual`](#allequal) * [`any`](#any) * [`arrayToCSV`](#arraytocsv) @@ -145,21 +145,21 @@ average(1, 2, 3); * [`intersectionWith`](#intersectionwith) * [`isSorted`](#issorted) * [`join`](#join) -* [`JSONtoCSV`](#jsontocsv-) +* [`JSONtoCSV`](#jsontocsv) * [`last`](#last) * [`longestItem`](#longestitem) -* [`mapObject`](#mapobject-) +* [`mapObject`](#mapobject) * [`maxN`](#maxn) * [`minN`](#minn) * [`none`](#none) * [`nthElement`](#nthelement) * [`offset`](#offset) * [`partition`](#partition) -* [`permutations`](#permutations-) +* [`permutations`](#permutations) * [`pull`](#pull) -* [`pullAtIndex`](#pullatindex-) -* [`pullAtValue`](#pullatvalue-) -* [`pullBy`](#pullby-) +* [`pullAtIndex`](#pullatindex) +* [`pullAtValue`](#pullatvalue) +* [`pullBy`](#pullby) * [`reducedFilter`](#reducedfilter) * [`reduceSuccessive`](#reducesuccessive) * [`reduceWhich`](#reducewhich) @@ -173,7 +173,7 @@ average(1, 2, 3); * [`sortedIndexBy`](#sortedindexby) * [`sortedLastIndex`](#sortedlastindex) * [`sortedLastIndexBy`](#sortedlastindexby) -* [`stableSort`](#stablesort-) +* [`stableSort`](#stablesort) * [`symmetricDifference`](#symmetricdifference) * [`symmetricDifferenceBy`](#symmetricdifferenceby) * [`symmetricDifferenceWith`](#symmetricdifferencewith) @@ -191,48 +191,48 @@ average(1, 2, 3); * [`uniqueElementsByRight`](#uniqueelementsbyright) * [`uniqueSymmetricDifference`](#uniquesymmetricdifference) * [`unzip`](#unzip) -* [`unzipWith`](#unzipwith-) +* [`unzipWith`](#unzipwith) * [`without`](#without) * [`xProd`](#xprod) * [`zip`](#zip) * [`zipObject`](#zipobject) -* [`zipWith`](#zipwith-) +* [`zipWith`](#zipwith)
- -### 🌐 Browser + +### 🌐 Browser
-View contents - -* [`arrayToHtmlList`](#arraytohtmllist) + View contents + + * [`arrayToHtmlList`](#arraytohtmllist) * [`bottomVisible`](#bottomvisible) -* [`copyToClipboard`](#copytoclipboard-) -* [`counter`](#counter-) +* [`copyToClipboard`](#copytoclipboard) +* [`counter`](#counter) * [`createElement`](#createelement) -* [`createEventHub`](#createeventhub-) +* [`createEventHub`](#createeventhub) * [`currentURL`](#currenturl) * [`detectDeviceType`](#detectdevicetype) * [`elementContains`](#elementcontains) -* [`elementIsVisibleInViewport`](#elementisvisibleinviewport-) +* [`elementIsVisibleInViewport`](#elementisvisibleinviewport) * [`getScrollPosition`](#getscrollposition) * [`getStyle`](#getstyle) * [`hasClass`](#hasclass) -* [`hashBrowser`](#hashbrowser-) +* [`hashBrowser`](#hashbrowser) * [`hide`](#hide) * [`httpsRedirect`](#httpsredirect) * [`insertAfter`](#insertafter) * [`insertBefore`](#insertbefore) * [`isBrowserTabFocused`](#isbrowsertabfocused) * [`nodeListToArray`](#nodelisttoarray) -* [`observeMutations`](#observemutations-) +* [`observeMutations`](#observemutations) * [`off`](#off) * [`on`](#on) -* [`onUserInputChange`](#onuserinputchange-) +* [`onUserInputChange`](#onuserinputchange) * [`prefix`](#prefix) * [`recordAnimationFrames`](#recordanimationframes) * [`redirect`](#redirect) -* [`runAsync`](#runasync-) +* [`runAsync`](#runasync) * [`scrollToTop`](#scrolltotop) * [`setStyle`](#setstyle) * [`show`](#show) @@ -242,26 +242,26 @@ average(1, 2, 3); * [`UUIDGeneratorBrowser`](#uuidgeneratorbrowser)
- -### ⏱️ Date + +### ⏱️ Date
-View contents - -* [`formatDuration`](#formatduration) + View contents + + * [`formatDuration`](#formatduration) * [`getColonTimeFromDate`](#getcolontimefromdate) * [`getDaysDiffBetweenDates`](#getdaysdiffbetweendates) * [`getMeridiemSuffixOfInteger`](#getmeridiemsuffixofinteger) * [`tomorrow`](#tomorrow)
- -### πŸŽ›οΈ Function + +### πŸŽ›οΈ Function
-View contents - -* [`attempt`](#attempt) + View contents + + * [`attempt`](#attempt) * [`bind`](#bind) * [`bindKey`](#bindkey) * [`chainAsync`](#chainasync) @@ -274,27 +274,27 @@ average(1, 2, 3); * [`delay`](#delay) * [`functionName`](#functionname) * [`hz`](#hz) -* [`memoize`](#memoize-) +* [`memoize`](#memoize) * [`negate`](#negate) * [`once`](#once) * [`partial`](#partial) * [`partialRight`](#partialright) * [`runPromisesInSeries`](#runpromisesinseries) * [`sleep`](#sleep) -* [`throttle`](#throttle-) +* [`throttle`](#throttle) * [`times`](#times) * [`uncurry`](#uncurry) * [`unfold`](#unfold) * [`when`](#when)
- -### βž— Math + +### βž— Math
-View contents - -* [`approximatelyEqual`](#approximatelyequal) + View contents + + * [`approximatelyEqual`](#approximatelyequal) * [`average`](#average) * [`averageBy`](#averageby) * [`binomialCoefficient`](#binomialcoefficient) @@ -302,7 +302,7 @@ average(1, 2, 3); * [`degreesToRads`](#degreestorads) * [`digitize`](#digitize) * [`distance`](#distance) -* [`elo`](#elo-) +* [`elo`](#elo) * [`factorial`](#factorial) * [`fibonacci`](#fibonacci) * [`gcd`](#gcd) @@ -313,7 +313,7 @@ average(1, 2, 3); * [`isEven`](#iseven) * [`isPrime`](#isprime) * [`lcm`](#lcm) -* [`luhnCheck`](#luhncheck-) +* [`luhnCheck`](#luhncheck) * [`maxBy`](#maxby) * [`median`](#median) * [`minBy`](#minby) @@ -333,13 +333,13 @@ average(1, 2, 3); * [`toSafeInteger`](#tosafeinteger)
- -### πŸ“¦ Node + +### πŸ“¦ Node
-View contents - -* [`atob`](#atob) + View contents + + * [`atob`](#atob) * [`btoa`](#btoa) * [`colorize`](#colorize) * [`hasFlags`](#hasflags) @@ -351,18 +351,18 @@ average(1, 2, 3); * [`UUIDGeneratorNode`](#uuidgeneratornode)
- -### πŸ—ƒοΈ Object + +### πŸ—ƒοΈ Object
-View contents - -* [`bindAll`](#bindall) + View contents + + * [`bindAll`](#bindall) * [`deepClone`](#deepclone) * [`deepFreeze`](#deepfreeze) * [`defaults`](#defaults) * [`dig`](#dig) -* [`equals`](#equals-) +* [`equals`](#equals) * [`findKey`](#findkey) * [`findLastKey`](#findlastkey) * [`flattenObject`](#flattenobject) @@ -390,20 +390,20 @@ average(1, 2, 3); * [`size`](#size) * [`transform`](#transform) * [`truthCheckCollection`](#truthcheckcollection) -* [`unflattenObject`](#unflattenobject-) +* [`unflattenObject`](#unflattenobject)
- -### πŸ“œ String + +### πŸ“œ String
-View contents - -* [`byteSize`](#bytesize) + View contents + + * [`byteSize`](#bytesize) * [`capitalize`](#capitalize) * [`capitalizeEveryWord`](#capitalizeeveryword) * [`CSVToArray`](#csvtoarray) -* [`CSVToJSON`](#csvtojson-) +* [`CSVToJSON`](#csvtojson) * [`decapitalize`](#decapitalize) * [`escapeHTML`](#escapehtml) * [`escapeRegExp`](#escaperegexp) @@ -421,24 +421,24 @@ average(1, 2, 3); * [`reverseString`](#reversestring) * [`sortCharactersInString`](#sortcharactersinstring) * [`splitLines`](#splitlines) -* [`stringPermutations`](#stringpermutations-) +* [`stringPermutations`](#stringpermutations) * [`stripHTMLTags`](#striphtmltags) * [`toCamelCase`](#tocamelcase) * [`toKebabCase`](#tokebabcase) * [`toSnakeCase`](#tosnakecase) * [`truncateString`](#truncatestring) * [`unescapeHTML`](#unescapehtml) -* [`URLJoin`](#urljoin-) +* [`URLJoin`](#urljoin) * [`words`](#words)
- -### πŸ“ƒ Type + +### πŸ“ƒ Type
-View contents - -* [`getType`](#gettype) + View contents + + * [`getType`](#gettype) * [`is`](#is) * [`isArrayLike`](#isarraylike) * [`isBoolean`](#isboolean) @@ -458,26 +458,26 @@ average(1, 2, 3); * [`isValidJSON`](#isvalidjson)
- -### πŸ”§ Utility + +### πŸ”§ Utility
-View contents - -* [`castArray`](#castarray) + View contents + + * [`castArray`](#castarray) * [`cloneRegExp`](#cloneregexp) * [`coalesce`](#coalesce) * [`coalesceFactory`](#coalescefactory) * [`extendHex`](#extendhex) * [`getURLParameters`](#geturlparameters) -* [`hexToRGB`](#hextorgb-) +* [`hexToRGB`](#hextorgb) * [`httpGet`](#httpget) * [`httpPost`](#httppost) * [`isBrowser`](#isbrowser) * [`mostPerformant`](#mostperformant) * [`nthArg`](#ntharg) * [`parseCookie`](#parsecookie) -* [`prettyBytes`](#prettybytes-) +* [`prettyBytes`](#prettybytes) * [`randomHexColorCode`](#randomhexcolorcode) * [`RGBToHex`](#rgbtohex) * [`serializeCookie`](#serializecookie) @@ -489,11 +489,10 @@ average(1, 2, 3); * [`yesNo`](#yesno)
- ---- - ## πŸ”Œ Adapter - -### ary + + +--- +## πŸ”Œ Adapter### ary Creates a function that accepts up to `n` arguments, ignoring any additional arguments. @@ -501,20 +500,19 @@ Call the provided function, `fn`, with up to `n` arguments, using `Array.slice(0 ```js const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); -``` +```
-Examples - -```js + Examples + + ```js const firstTwoMax = ary(Math.max, 2); [[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)); // [6, 8, 10] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### call @@ -524,12 +522,12 @@ Use a closure to call a stored key with stored arguments. ```js const call = (key, ...args) => context => context[key](...args); -``` - -
-Examples +``` -```js +
+ Examples + + ```js Promise.resolve([1, 2, 3]) .then(call('map', x => 2 * x)) .then(console.log); //[ 2, 4, 6 ] @@ -540,9 +538,8 @@ Promise.resolve([1, 2, 3]) ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### collectInto @@ -552,12 +549,12 @@ Given a function, return a closure that collects all inputs into an array-accept ```js const collectInto = fn => (...args) => fn(args); -``` - -
-Examples +``` -```js +
+ Examples + + ```js const Pall = collectInto(Promise.all.bind(Promise)); let p1 = Promise.resolve(1); let p2 = Promise.resolve(2); @@ -566,9 +563,8 @@ Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds) ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### flip @@ -578,12 +574,12 @@ Return a closure that takes variadic inputs, and splices the last argument to ma ```js const flip = fn => (first, ...rest) => fn(...rest, first); -``` - -
-Examples +``` -```js +
+ Examples + + ```js let a = { name: 'John Smith' }; let b = {}; const mergeFrom = flip(Object.assign); @@ -594,9 +590,8 @@ Object.assign(b, a); // == b ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### over @@ -606,20 +601,19 @@ Use `Array.map()` and `Function.apply()` to apply each function to the given arg ```js const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); -``` +```
-Examples - -```js + Examples + + ```js const minMax = over(Math.min, Math.max); minMax(1, 2, 3, 4, 5); // [1,5] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### overArgs @@ -629,12 +623,12 @@ Use `Array.map()` to apply `transforms` to `args` in combination with the spread ```js const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val))); -``` +```
-Examples - -```js + Examples + + ```js const square = n => n * n; const double = n => n * 2; const fn = overArgs((x, y) => [x, y], [square, double]); @@ -642,9 +636,8 @@ fn(9, 3); // [81, 6] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### pipeAsyncFunctions @@ -656,12 +649,12 @@ All functions must be unary. ```js const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); -``` +```
-Examples - -```js + Examples + + ```js const sum = pipeAsyncFunctions( x => x + 1, x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)), @@ -674,9 +667,8 @@ const sum = pipeAsyncFunctions( ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### pipeFunctions @@ -687,12 +679,12 @@ The first (leftmost) function can accept one or more arguments; the remaining fu ```js const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); -``` +```
-Examples - -```js + Examples + + ```js const add5 = x => x + 5; const multiply = (x, y) => x * y; const multiplyAndAdd5 = pipeFunctions(multiply, add5); @@ -700,9 +692,8 @@ multiplyAndAdd5(5, 2); // 15 ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### promisify @@ -718,20 +709,19 @@ const promisify = func => (...args) => new Promise((resolve, reject) => func(...args, (err, result) => (err ? reject(err) : resolve(result))) ); -``` +```
-Examples - -```js + 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) - + +[⬆ Back to top](#table-of-contents) ### rearg @@ -741,12 +731,12 @@ Use `Array.map()` to reorder arguments based on `indexes` in combination with th ```js const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i])); -``` +```
-Examples - -```js + Examples + + ```js var rearged = rearg( function(a, b, c) { return [a, b, c]; @@ -757,9 +747,8 @@ rearged('b', 'c', 'a'); // ['a', 'b', 'c'] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### spreadOver @@ -769,20 +758,19 @@ Use closures and the spread operator (`...`) to map the array of arguments to th ```js const spreadOver = fn => argsArr => fn(...argsArr); -``` - -
-Examples +``` -```js +
+ Examples + + ```js const arrayMax = spreadOver(Math.max); arrayMax([1, 2, 3]); // 3 ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### unary @@ -792,23 +780,22 @@ Call the provided function, `fn`, with just the first argument given. ```js const unary = fn => val => fn(val); -``` +```
-Examples - -```js + Examples + + ```js ['6', '8', '10'].map(unary(parseInt)); // [6, 8, 10] ```
+ +[⬆ Back to top](#table-of-contents) -
[⬆ Back to top](#table-of-contents) - ---- - ## πŸ“š Array - -### all + +--- +## πŸ“š Array### all Returns `true` if the provided predicate function returns `true` for all elements in a collection, `false` otherwise. @@ -817,20 +804,19 @@ Omit the second argument, `fn`, to use `Boolean` as a default. ```js const all = (arr, fn = Boolean) => arr.every(fn); -``` +```
-Examples - -```js + Examples + + ```js all([4, 2, 3], x => x > 1); // true all([1, 2, 3]); // true ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### allEqual @@ -840,20 +826,19 @@ Use `Array.every()` to check if all the elements of the array are the same as th ```js const allEqual = arr => arr.every(val => val === arr[0]); -``` +```
-Examples - -```js + Examples + + ```js allEqual([1, 2, 3, 4, 5, 6]); // false allEqual([1, 1, 1, 1]); // true ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### any @@ -864,20 +849,19 @@ Omit the second argument, `fn`, to use `Boolean` as a default. ```js const any = (arr, fn = Boolean) => arr.some(fn); -``` +```
-Examples - -```js + Examples + + ```js any([0, 1, 2, 0], x => x >= 2); // true any([0, 0, 1, 0]); // true ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### arrayToCSV @@ -890,20 +874,19 @@ Omit the second argument, `delimiter`, to use a default delimiter of `,`. ```js const arrayToCSV = (arr, delimiter = ',') => arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n'); -``` +```
-Examples - -```js + Examples + + ```js arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"' arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"' ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### bifurcate @@ -914,19 +897,18 @@ Use `Array.reduce()` and `Array.push()` to add elements to groups, based on `fil ```js const bifurcate = (arr, filter) => arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]); -``` +```
-Examples - -```js + Examples + + ```js bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### bifurcateBy @@ -937,19 +919,18 @@ Use `Array.reduce()` and `Array.push()` to add elements to groups, based on the ```js const bifurcateBy = (arr, fn) => arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]); -``` +```
-Examples - -```js + Examples + + ```js bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### chunk @@ -964,19 +945,18 @@ const chunk = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => arr.slice(i * size, i * size + size) ); -``` +```
-Examples - -```js + Examples + + ```js chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### compact @@ -986,19 +966,18 @@ Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `u ```js const compact = arr => arr.filter(Boolean); -``` +```
-Examples - -```js + 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) - + +[⬆ Back to top](#table-of-contents) ### countBy @@ -1013,20 +992,19 @@ const countBy = (arr, fn) => acc[val] = (acc[val] || 0) + 1; return acc; }, {}); -``` +```
-Examples - -```js + Examples + + ```js countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2} countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1} ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### countOccurrences @@ -1036,19 +1014,18 @@ Use `Array.reduce()` to increment a counter each time you encounter the specific ```js const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); -``` +```
-Examples - -```js + Examples + + ```js countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3 ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### deepFlatten @@ -1060,19 +1037,18 @@ Recursively flatten each element that is an array. ```js const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); -``` +```
-Examples - -```js + Examples + + ```js deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### difference @@ -1085,19 +1061,18 @@ const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }; -``` +```
-Examples - -```js + Examples + + ```js difference([1, 2, 3], [1, 2, 4]); // [3] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### differenceBy @@ -1110,20 +1085,19 @@ const differenceBy = (a, b, fn) => { const s = new Set(b.map(v => fn(v))); return a.filter(x => !s.has(fn(x))); }; -``` +```
-Examples - -```js + Examples + + ```js differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2] differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [ { x: 2 } ] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### differenceWith @@ -1133,19 +1107,18 @@ Use `Array.filter()` and `Array.findIndex()` to find the appropriate values. ```js const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1); -``` +```
-Examples - -```js + Examples + + ```js differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### drop @@ -1155,21 +1128,20 @@ Use `Array.slice()` to slice the remove the specified number of elements from th ```js const drop = (arr, n = 1) => arr.slice(n); -``` +```
-Examples - -```js + Examples + + ```js drop([1, 2, 3]); // [2,3] drop([1, 2, 3], 2); // [3] drop([1, 2, 3], 42); // [] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### dropRight @@ -1179,21 +1151,20 @@ Use `Array.slice()` to slice the remove the specified number of elements from th ```js const dropRight = (arr, n = 1) => arr.slice(0, -n); -``` +```
-Examples - -```js + 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) - + +[⬆ Back to top](#table-of-contents) ### dropRightWhile @@ -1207,19 +1178,18 @@ const dropRightWhile = (arr, func) => { while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1); return arr; }; -``` +```
-Examples - -```js + Examples + + ```js dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### dropWhile @@ -1233,19 +1203,18 @@ const dropWhile = (arr, func) => { while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); return arr; }; -``` +```
-Examples - -```js + Examples + + ```js dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### everyNth @@ -1255,19 +1224,18 @@ Use `Array.filter()` to create a new array that contains every nth element of a ```js const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); -``` +```
-Examples - -```js + Examples + + ```js everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### filterNonUnique @@ -1277,19 +1245,18 @@ Use `Array.filter()` for an array containing only the unique values. ```js const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); -``` +```
-Examples - -```js + Examples + + ```js filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### filterNonUniqueBy @@ -1301,12 +1268,12 @@ The comparator function takes four arguments: the values of the two elements bei ```js const filterNonUniqueBy = (arr, fn) => arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j))); -``` +```
-Examples - -```js + Examples + + ```js filterNonUniqueBy( [ { id: 0, value: 'a' }, @@ -1320,9 +1287,8 @@ filterNonUniqueBy( ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### findLast @@ -1332,19 +1298,18 @@ Use `Array.filter()` to remove elements for which `fn` returns falsey values, `A ```js const findLast = (arr, fn) => arr.filter(fn).pop(); -``` +```
-Examples - -```js + Examples + + ```js findLast([1, 2, 3, 4], n => n % 2 === 1); // 3 ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### findLastIndex @@ -1359,19 +1324,18 @@ const findLastIndex = (arr, fn) => .map((val, i) => [i, val]) .filter(([i, val]) => fn(val, i, arr)) .pop()[0]; -``` +```
-Examples - -```js + Examples + + ```js findLastIndex([1, 2, 3, 4], n => n % 2 === 1); // 2 (index of the value 3) ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### flatten @@ -1385,20 +1349,19 @@ Omit the second argument, `depth` to flatten only to a depth of `1` (single flat ```js const flatten = (arr, depth = 1) => arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []); -``` +```
-Examples - -```js + Examples + + ```js flatten([1, [2], 3, 4]); // [1, 2, 3, 4] flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### forEachRight @@ -1412,19 +1375,18 @@ const forEachRight = (arr, callback) => .slice(0) .reverse() .forEach(callback); -``` +```
-Examples - -```js + Examples + + ```js forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1' ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### groupBy @@ -1439,20 +1401,19 @@ const groupBy = (arr, fn) => acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {}); -``` +```
-Examples - -```js + 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) - + +[⬆ Back to top](#table-of-contents) ### head @@ -1462,19 +1423,18 @@ Use `arr[0]` to return the first element of the passed array. ```js const head = arr => arr[0]; -``` +```
-Examples - -```js + Examples + + ```js head([1, 2, 3]); // 1 ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### indexOfAll @@ -1485,20 +1445,19 @@ Return the array of indices. ```js const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []); -``` +```
-Examples - -```js + Examples + + ```js indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3] indexOfAll([1, 2, 3], 4); // [] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### initial @@ -1508,19 +1467,18 @@ Use `arr.slice(0,-1)` to return all but the last element of the array. ```js const initial = arr => arr.slice(0, -1); -``` +```
-Examples - -```js + Examples + + ```js initial([1, 2, 3]); // [1,2] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### initialize2DArray @@ -1531,19 +1489,18 @@ Use `Array.map()` to generate h rows where each is a new array of size w initial ```js const initialize2DArray = (w, h, val = null) => Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val)); -``` +```
-Examples - -```js + Examples + + ```js initialize2DArray(2, 2, 0); // [[0,0], [0,0]] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### initializeArrayWithRange @@ -1556,21 +1513,20 @@ You can omit `step` to use a default value of `1`. ```js const initializeArrayWithRange = (end, start = 0, step = 1) => Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) => i * step + start); -``` +```
-Examples - -```js + Examples + + ```js initializeArrayWithRange(5); // [0,1,2,3,4,5] initializeArrayWithRange(7, 3); // [3,4,5,6,7] initializeArrayWithRange(9, 0, 2); // [0,2,4,6,8] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### initializeArrayWithRangeRight @@ -1585,21 +1541,20 @@ const initializeArrayWithRangeRight = (end, start = 0, step = 1) => Array.from({ length: Math.ceil((end + 1 - start) / step) }).map( (v, i, arr) => (arr.length - i - 1) * step + start ); -``` +```
-Examples - -```js + Examples + + ```js initializeArrayWithRangeRight(5); // [5,4,3,2,1,0] initializeArrayWithRangeRight(7, 3); // [7,6,5,4,3] initializeArrayWithRangeRight(9, 0, 2); // [8,6,4,2,0] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### initializeArrayWithValues @@ -1610,19 +1565,18 @@ You can omit `val` to use a default value of `0`. ```js const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); -``` +```
-Examples - -```js + Examples + + ```js initializeArrayWithValues(5, 2); // [2,2,2,2,2] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### initializeNDArray @@ -1636,20 +1590,19 @@ const initializeNDArray = (val, ...args) => args.length === 0 ? val : Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1))); -``` +```
-Examples - -```js + Examples + + ```js initializeNDArray(1, 3); // [1,1,1] initializeNDArray(5, 2, 2, 2); // [[[5,5],[5,5]],[[5,5],[5,5]]] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### intersection @@ -1662,19 +1615,18 @@ const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); }; -``` +```
-Examples - -```js + Examples + + ```js intersection([1, 2, 3], [4, 3, 2]); // [2,3] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### intersectionBy @@ -1687,19 +1639,18 @@ const intersectionBy = (a, b, fn) => { const s = new Set(b.map(fn)); return a.filter(x => s.has(fn(x))); }; -``` +```
-Examples - -```js + Examples + + ```js intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### intersectionWith @@ -1709,19 +1660,18 @@ Use `Array.filter()` and `Array.findIndex()` in combination with the provided co ```js const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1); -``` +```
-Examples - -```js + Examples + + ```js intersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1.5, 3, 0] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isSorted @@ -1740,21 +1690,20 @@ const isSorted = arr => { else if ((val - arr[i + 1]) * direction > 0) return 0; } }; -``` +```
-Examples - -```js + Examples + + ```js isSorted([0, 1, 2, 2]); // 1 isSorted([4, 3, 2]); // -1 isSorted([4, 3, 5]); // 0 ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### join @@ -1775,21 +1724,20 @@ const join = (arr, separator = ',', end = separator) => : acc + val + separator, '' ); -``` +```
-Examples - -```js + Examples + + ```js join(['pen', 'pineapple', 'apple', 'pen'], ',', '&'); // "pen,pineapple,apple&pen" join(['pen', 'pineapple', 'apple', 'pen'], ','); // "pen,pineapple,apple,pen" join(['pen', 'pineapple', 'apple', 'pen']); // "pen,pineapple,apple,pen" ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### JSONtoCSV ![advanced](/advanced.svg) @@ -1811,20 +1759,19 @@ const JSONtoCSV = (arr, columns, delimiter = ',') => ) ) ].join('\n'); -``` +```
-Examples - -```js + Examples + + ```js JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b']); // 'a,b\n"1","2"\n"3","4"\n"6",""\n"","7"' JSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';'); // 'a;b\n"1";"2"\n"3";"4"\n"6";""\n"";"7"' ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### last @@ -1834,19 +1781,18 @@ Use `arr.length - 1` to compute the index of the last element of the given array ```js const last = arr => arr[arr.length - 1]; -``` +```
-Examples - -```js + Examples + + ```js last([1, 2, 3]); // 3 ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### longestItem @@ -1859,12 +1805,12 @@ Use `Array.reduce()`, comparing the `length` of objects to find the longest one. ```js const longestItem = (val, ...vals) => [val, ...vals].reduce((a, x) => (x.length > a.length ? x : a)); -``` +```
-Examples - -```js + Examples + + ```js longestItem('this', 'is', 'a', 'testcase'); // 'testcase' longestItem(...['a', 'ab', 'abc']); // 'abc' longestItem(...['a', 'ab', 'abc'], 'abcd'); // 'abcd' @@ -1873,9 +1819,8 @@ longestItem([1, 2, 3], 'foobar'); // 'foobar' ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### mapObject ![advanced](/advanced.svg) @@ -1888,20 +1833,19 @@ const mapObject = (arr, fn) => (a => ( (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) ))(); -``` +```
-Examples - -```js + 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) - + +[⬆ Back to top](#table-of-contents) ### maxN @@ -1913,20 +1857,19 @@ Omit the second argument, `n`, to get a one-element array. ```js const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); -``` +```
-Examples - -```js + Examples + + ```js maxN([1, 2, 3]); // [3] maxN([1, 2, 3], 2); // [3,2] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### minN @@ -1938,19 +1881,19 @@ Omit the second argument, `n`, to get a one-element array. ```js const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); -``` -
-Examples +``` -```js +
+ Examples + + ```js minN([1, 2, 3]); // [1] minN([1, 2, 3], 2); // [1,2] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### none @@ -1961,20 +1904,19 @@ Omit the second argument, `fn`, to use `Boolean` as a default. ```js const none = (arr, fn = Boolean) => !arr.some(fn); -``` +```
-Examples - -```js + Examples + + ```js none([0, 1, 3, 0], x => x == 2); // true none([0, 0, 0]); // true ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### nthElement @@ -1986,20 +1928,19 @@ Omit the second argument, `n`, to get the first element of the array. ```js const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0]; -``` +```
-Examples - -```js + Examples + + ```js nthElement(['a', 'b', 'c'], 1); // 'b' nthElement(['a', 'b', 'b'], -3); // 'a' ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### offset @@ -2011,20 +1952,19 @@ If `offset` is negative, the elements will be moved from end to start. ```js const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)]; -``` +```
-Examples - -```js + Examples + + ```js offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2] offset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### partition @@ -2042,20 +1982,19 @@ const partition = (arr, fn) => }, [[], []] ); -``` +```
-Examples - -```js + Examples + + ```js const users = [{ user: 'barney', age: 36, active: false }, { user: 'fred', age: 40, active: true }]; partition(users, o => o.active); // [[{ 'user': 'fred', 'age': 40, 'active': true }],[{ 'user': 'barney', 'age': 36, 'active': false }]] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### permutations ![advanced](/advanced.svg) @@ -2079,19 +2018,18 @@ const permutations = arr => { [] ); }; -``` +```
-Examples - -```js + Examples + + ```js permutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### pull @@ -2109,20 +2047,19 @@ const pull = (arr, ...args) => { arr.length = 0; pulled.forEach(v => arr.push(v)); }; -``` +```
-Examples - -```js + Examples + + ```js let myArray = ['a', 'b', 'c', 'a', 'b', 'c']; pull(myArray, 'a', 'c'); // myArray = [ 'b', 'b' ] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### pullAtIndex ![advanced](/advanced.svg) @@ -2142,20 +2079,19 @@ const pullAtIndex = (arr, pullArr) => { pulled.forEach(v => arr.push(v)); return removed; }; -``` +```
-Examples - -```js + Examples + + ```js let myArray = ['a', 'b', 'c', 'd']; let pulled = pullAtIndex(myArray, [1, 3]); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### pullAtValue ![advanced](/advanced.svg) @@ -2174,20 +2110,19 @@ const pullAtValue = (arr, pullArr) => { mutateTo.forEach(v => arr.push(v)); return removed; }; -``` +```
-Examples - -```js + Examples + + ```js let myArray = ['a', 'b', 'c', 'd']; let pulled = pullAtValue(myArray, ['b', 'd']); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### pullBy ![advanced](/advanced.svg) @@ -2208,20 +2143,19 @@ const pullBy = (arr, ...args) => { arr.length = 0; pulled.forEach(v => arr.push(v)); }; -``` +```
-Examples - -```js + Examples + + ```js var myArray = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 1 }]; pullBy(myArray, [{ x: 1 }, { x: 3 }], o => o.x); // myArray = [{ x: 2 }] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### reducedFilter @@ -2238,12 +2172,12 @@ const reducedFilter = (data, keys, fn) => return acc; }, {}) ); -``` +```
-Examples - -```js + Examples + + ```js const data = [ { id: 1, @@ -2261,9 +2195,8 @@ reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: ' ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### reduceSuccessive @@ -2274,19 +2207,18 @@ Use `Array.reduce()` to apply the given function to the given array, storing eac ```js const reduceSuccessive = (arr, fn, acc) => arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]); -``` +```
-Examples - -```js + Examples + + ```js reduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) => acc + val, 0); // [0, 1, 3, 6, 10, 15, 21] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### reduceWhich @@ -2298,12 +2230,12 @@ You can omit the second parameter, `comparator`, to use the default one that ret ```js const reduceWhich = (arr, comparator = (a, b) => a - b) => arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a)); -``` +```
-Examples - -```js + Examples + + ```js reduceWhich([1, 3, 2]); // 1 reduceWhich([1, 3, 2], (a, b) => b - a); // 3 reduceWhich( @@ -2313,9 +2245,8 @@ reduceWhich( ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### reject @@ -2323,20 +2254,19 @@ Takes a predicate and array, like `Array.filter()`, but only keeps `x` if `pred( ```js const reject = (pred, array) => array.filter((...args) => !pred(...args)); -``` +```
-Examples - -```js + Examples + + ```js reject(x => x % 2 === 0, [1, 2, 3, 4, 5]); // [1, 3, 5] reject(word => word.length > 4, ['Apple', 'Pear', 'Kiwi', 'Banana']); // ['Pear', 'Kiwi'] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### remove @@ -2353,19 +2283,18 @@ const remove = (arr, func) => return acc.concat(val); }, []) : []; -``` +```
-Examples - -```js + Examples + + ```js remove([1, 2, 3, 4], n => n % 2 === 0); // [2, 4] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### sample @@ -2376,19 +2305,18 @@ This method also works with strings. ```js const sample = arr => arr[Math.floor(Math.random() * arr.length)]; -``` +```
-Examples - -```js + Examples + + ```js sample([3, 7, 9, 11]); // 9 ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### sampleSize @@ -2407,20 +2335,19 @@ const sampleSize = ([...arr], n = 1) => { } return arr.slice(0, n); }; -``` +```
-Examples - -```js + Examples + + ```js sampleSize([1, 2, 3], 2); // [3,1] sampleSize([1, 2, 3], 4); // [2,3,1] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### shuffle @@ -2437,20 +2364,19 @@ const shuffle = ([...arr]) => { } return arr; }; -``` +```
-Examples - -```js + Examples + + ```js const foo = [1, 2, 3]; shuffle(foo); // [2,3,1], foo = [1,2,3] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### similarity @@ -2460,19 +2386,18 @@ Use `Array.filter()` to remove values that are not part of `values`, determined ```js const similarity = (arr, values) => arr.filter(v => values.includes(v)); -``` +```
-Examples - -```js + Examples + + ```js similarity([1, 2, 3], [1, 2, 4]); // [1,2] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### sortedIndex @@ -2487,20 +2412,19 @@ const sortedIndex = (arr, n) => { const index = arr.findIndex(el => (isDescending ? n >= el : n <= el)); return index === -1 ? arr.length : index; }; -``` +```
-Examples - -```js + Examples + + ```js sortedIndex([5, 3, 2, 1], 4); // 1 sortedIndex([30, 50], 40); // 1 ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### sortedIndexBy @@ -2516,19 +2440,18 @@ const sortedIndexBy = (arr, n, fn) => { const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el))); return index === -1 ? arr.length : index; }; -``` +```
-Examples - -```js + Examples + + ```js sortedIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 0 ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### sortedLastIndex @@ -2543,19 +2466,18 @@ const sortedLastIndex = (arr, n) => { const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el)); return index === -1 ? 0 : arr.length - index; }; -``` +```
-Examples - -```js + Examples + + ```js sortedLastIndex([10, 20, 30, 30, 40], 30); // 4 ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### sortedLastIndexBy @@ -2575,19 +2497,18 @@ const sortedLastIndexBy = (arr, n, fn) => { .findIndex(el => (isDescending ? val <= el : val >= el)); return index === -1 ? 0 : arr.length - index; }; -``` +```
-Examples - -```js + Examples + + ```js sortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 1 ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### stableSort ![advanced](/advanced.svg) @@ -2604,20 +2525,19 @@ const stableSort = (arr, compare) => .map((item, index) => ({ item, index })) .sort((a, b) => compare(a.item, b.item) || a.index - b.index) .map(({ item }) => item); -``` +```
-Examples - -```js + Examples + + ```js const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const stable = stableSort(arr, () => 0); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### symmetricDifference @@ -2631,20 +2551,19 @@ const symmetricDifference = (a, b) => { sB = new Set(b); return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; }; -``` +```
-Examples - -```js + Examples + + ```js symmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4] symmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 2, 3] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### symmetricDifferenceBy @@ -2658,19 +2577,18 @@ const symmetricDifferenceBy = (a, b, fn) => { sB = new Set(b.map(v => fn(v))); return [...a.filter(x => !sB.has(fn(x))), ...b.filter(x => !sA.has(fn(x)))]; }; -``` +```
-Examples - -```js + Examples + + ```js symmetricDifferenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [ 1.2, 3.4 ] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### symmetricDifferenceWith @@ -2683,12 +2601,12 @@ const symmetricDifferenceWith = (arr, val, comp) => [ ...arr.filter(a => val.findIndex(b => comp(a, b)) === -1), ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1) ]; -``` +```
-Examples - -```js + Examples + + ```js symmetricDifferenceWith( [1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], @@ -2697,9 +2615,8 @@ symmetricDifferenceWith( ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### tail @@ -2709,20 +2626,19 @@ Return `Array.slice(1)` if the array's `length` is more than `1`, otherwise, ret ```js const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); -``` +```
-Examples - -```js + Examples + + ```js tail([1, 2, 3]); // [2,3] tail([1]); // [1] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### take @@ -2732,20 +2648,19 @@ Use `Array.slice()` to create a slice of the array with `n` elements taken from ```js const take = (arr, n = 1) => arr.slice(0, n); -``` +```
-Examples - -```js + Examples + + ```js take([1, 2, 3], 5); // [1, 2, 3] take([1, 2, 3], 0); // [] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### takeRight @@ -2755,20 +2670,19 @@ Use `Array.slice()` to create a slice of the array with `n` elements taken from ```js const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); -``` +```
-Examples - -```js + Examples + + ```js takeRight([1, 2, 3], 2); // [ 2, 3 ] takeRight([1, 2, 3]); // [3] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### takeRightWhile @@ -2783,19 +2697,18 @@ const takeRightWhile = (arr, func) => { if (func(arr[i])) return arr.reverse().slice(arr.length - i, arr.length); return arr; }; -``` +```
-Examples - -```js + Examples + + ```js takeRightWhile([1, 2, 3, 4], n => n < 3); // [3, 4] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### takeWhile @@ -2809,19 +2722,18 @@ const takeWhile = (arr, func) => { for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i); return arr; }; -``` +```
-Examples - -```js + Examples + + ```js takeWhile([1, 2, 3, 4], n => n >= 3); // [1, 2] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### toHash @@ -2836,12 +2748,12 @@ const toHash = (object, key) => (acc, data, index) => ((acc[!key ? index : data[key]] = data), acc), {} ); -``` +```
-Examples - -```js + Examples + + ```js toHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 1: 1 } toHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } } // A more in depth example: @@ -2858,9 +2770,8 @@ managers; // [ { manager:1, employees: [ { id: 2, first: "Joe" }, { id: 3, first ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### union @@ -2870,19 +2781,18 @@ Create a `Set` with all values of `a` and `b` and convert to an array. ```js const union = (a, b) => Array.from(new Set([...a, ...b])); -``` +```
-Examples - -```js + Examples + + ```js union([1, 2, 3], [4, 3, 2]); // [1,2,3,4] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### unionBy @@ -2897,19 +2807,18 @@ const unionBy = (a, b, fn) => { const s = new Set(a.map(v => fn(v))); return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))])); }; -``` +```
-Examples - -```js + Examples + + ```js unionBy([2.1], [1.2, 2.3], Math.floor); // [2.1, 1.2] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### unionWith @@ -2920,19 +2829,18 @@ Create a `Set` with all values of `a` and values in `b` for which the comparator ```js const unionWith = (a, b, comp) => Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)])); -``` +```
-Examples - -```js + Examples + + ```js unionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2, 1.5, 3, 0, 3.9] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### uniqueElements @@ -2942,19 +2850,18 @@ Use ES6 `Set` and the `...rest` operator to discard all duplicated values. ```js const uniqueElements = arr => [...new Set(arr)]; -``` +```
-Examples - -```js + Examples + + ```js uniqueElements([1, 2, 2, 3, 4, 4, 5]); // [1,2,3,4,5] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### uniqueElementsBy @@ -2969,12 +2876,12 @@ const uniqueElementsBy = (arr, fn) => if (!acc.some(x => fn(v, x))) acc.push(v); return acc; }, []); -``` +```
-Examples - -```js + Examples + + ```js uniqueElementsBy( [ { id: 0, value: 'a' }, @@ -2988,9 +2895,8 @@ uniqueElementsBy( ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### uniqueElementsByRight @@ -3005,12 +2911,12 @@ const uniqueElementsByRight = (arr, fn) => if (!acc.some(x => fn(v, x))) acc.push(v); return acc; }, []); -``` +```
-Examples - -```js + Examples + + ```js uniqueElementsByRight( [ { id: 0, value: 'a' }, @@ -3024,9 +2930,8 @@ uniqueElementsByRight( ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### uniqueSymmetricDifference @@ -3038,20 +2943,19 @@ Use `Array.filter()` and `Array.includes()` on each array to remove values conta const uniqueSymmetricDifference = (a, b) => [ ...new Set([...a.filter(v => !b.includes(v)), ...b.filter(v => !a.includes(v))]) ]; -``` +```
-Examples - -```js + Examples + + ```js uniqueSymmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4] uniqueSymmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 3] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### unzip @@ -3068,20 +2972,19 @@ const unzip = arr => length: Math.max(...arr.map(x => x.length)) }).map(x => []) ); -``` +```
-Examples - -```js + Examples + + ```js unzip([['a', 1, true], ['b', 2, false]]); //[['a', 'b'], [1, 2], [true, false]] unzip([['a', 1, true], ['b', 2]]); //[['a', 'b'], [1, 2], [true]] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### unzipWith ![advanced](/advanced.svg) @@ -3101,19 +3004,18 @@ const unzipWith = (arr, fn) => }).map(x => []) ) .map(val => fn(...val)); -``` +```
-Examples - -```js + Examples + + ```js unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)); // [3, 30, 300] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### without @@ -3125,19 +3027,18 @@ _(For a snippet that mutates the original array see [`pull`](#pull))_ ```js const without = (arr, ...args) => arr.filter(v => !args.includes(v)); -``` +```
-Examples - -```js + Examples + + ```js without([2, 1, 2, 3], 1, 2); // [3] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### xProd @@ -3147,19 +3048,18 @@ Use `Array.reduce()`, `Array.map()` and `Array.concat()` to produce every possib ```js const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []); -``` +```
-Examples - -```js + Examples + + ```js xProd([1, 2], ['a', 'b']); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] ```
- -
[⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### zip @@ -3176,20 +3076,19 @@ const zip = (...arrays) => { return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]); }); }; -``` +```
-Examples - -```js + 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) - + +[⬆ Back to top](#table-of-contents) ### zipObject @@ -3200,20 +3099,19 @@ Since an object can have undefined values but not undefined property pointers, t ```js const zipObject = (props, values) => props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {}); -``` +```
-Examples - -```js + 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) - + +[⬆ Back to top](#table-of-contents) ### zipWith ![advanced](/advanced.svg) @@ -3233,12 +3131,12 @@ const zipWith = (...array) => { (_, i) => (fn ? fn(...array.map(a => a[i])) : array.map(a => a[i])) ); }; -``` +```
-Examples - -```js + Examples + + ```js zipWith([1, 2], [10, 20], [100, 200], (a, b, c) => a + b + c); // [111,222] zipWith( [1, 2, 3], @@ -3249,13 +3147,12 @@ zipWith( ```
+ +[⬆ Back to top](#table-of-contents) -
[⬆ Back to top](#table-of-contents) - ---- - ## 🌐 Browser - -### arrayToHtmlList + +--- +## 🌐 Browser### arrayToHtmlList Converts the given array elements into `
  • ` tags and appends them to the list of the given id. @@ -3267,19 +3164,18 @@ const arrayToHtmlList = (arr, listID) => (el = document.querySelector('#' + listID)), (el.innerHTML += arr.map(item => `
  • ${item}
  • `).join('')) ))(); -``` +```
    -Examples - -```js + Examples + + ```js arrayToHtmlList(['item 1', 'item 2'], 'myListID'); ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### bottomVisible @@ -3291,19 +3187,18 @@ Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of t const bottomVisible = () => document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight); -``` +```
    -Examples - -```js + Examples + + ```js bottomVisible(); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### copyToClipboard ![advanced](/advanced.svg) @@ -3335,19 +3230,18 @@ const copyToClipboard = str => { document.getSelection().addRange(selected); } }; -``` +```
    -Examples - -```js + Examples + + ```js copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard. ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### counter ![advanced](/advanced.svg) @@ -3371,19 +3265,18 @@ const counter = (selector, start, end, step = 1, duration = 2000) => { }, Math.abs(Math.floor(duration / (end - start)))); return timer; }; -``` +```
    -Examples - -```js + Examples + + ```js counter('#my-id', 1, 1000, 5, 2000); // Creates a 2-second timer for the element with id="my-id" ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### createElement @@ -3400,12 +3293,12 @@ const createElement = str => { el.innerHTML = str; return el.firstElementChild; }; -``` +```
    -Examples - -```js + Examples + + ```js const el = createElement( `

    Hello!

    @@ -3415,9 +3308,8 @@ console.log(el.className); // 'container' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### createEventHub ![advanced](/advanced.svg) @@ -3444,12 +3336,12 @@ const createEventHub = () => ({ if (i > -1) this.hub[event].splice(i, 1); } }); -``` +```
    -Examples - -```js + Examples + + ```js const handler = data => console.log(data); const hub = createEventHub(); let increment = 0; @@ -3469,9 +3361,8 @@ hub.off('message', handler); ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### currentURL @@ -3481,19 +3372,18 @@ Use `window.location.href` to get current URL. ```js const currentURL = () => window.location.href; -``` +```
    -Examples - -```js + Examples + + ```js currentURL(); // 'https://google.com' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### detectDeviceType @@ -3506,19 +3396,18 @@ const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop'; -``` +```
    -Examples - -```js + Examples + + ```js detectDeviceType(); // "Mobile" or "Desktop" ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### elementContains @@ -3528,20 +3417,19 @@ Check that `parent` is not the same element as `child`, use `parent.contains(chi ```js const elementContains = (parent, child) => parent !== child && parent.contains(child); -``` +```
    -Examples - -```js + Examples + + ```js elementContains(document.querySelector('head'), document.querySelector('title')); // true elementContains(document.querySelector('body'), document.querySelector('body')); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### elementIsVisibleInViewport ![advanced](/advanced.svg) @@ -3561,21 +3449,20 @@ const elementIsVisibleInViewport = (el, partiallyVisible = false) => { ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }; -``` +```
    -Examples - -```js + 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) - + +[⬆ Back to top](#table-of-contents) ### getScrollPosition @@ -3589,19 +3476,18 @@ const getScrollPosition = (el = window) => ({ x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop }); -``` +```
    -Examples - -```js + Examples + + ```js getScrollPosition(); // {x: 0, y: 200} ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### getStyle @@ -3611,19 +3497,18 @@ Use `Window.getComputedStyle()` to get the value of the CSS rule for the specifi ```js const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]; -``` +```
    -Examples - -```js + Examples + + ```js getStyle(document.querySelector('p'), 'font-size'); // '16px' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### hasClass @@ -3633,19 +3518,18 @@ Use `element.classList.contains()` to check if the element has the specified cla ```js const hasClass = (el, className) => el.classList.contains(className); -``` +```
    -Examples - -```js + Examples + + ```js hasClass(document.querySelector('p.special'), 'special'); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### hashBrowser ![advanced](/advanced.svg) @@ -3662,19 +3546,18 @@ const hashBrowser = val => hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8)); return hexes.join(''); }); -``` +```
    -Examples - -```js + Examples + + ```js hashBrowser(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### hide @@ -3684,19 +3567,18 @@ Use `NodeList.prototype.forEach()` to apply `display: none` to each element spec ```js const hide = els => els.forEach(e => (e.style.display = 'none')); -``` +```
    -Examples - -```js + Examples + + ```js hide(document.querySelectorAll('img')); // Hides all elements on the page ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### httpsRedirect @@ -3708,19 +3590,18 @@ Use `location.protocol` to get the protocol currently being used. If it's not HT const httpsRedirect = () => { if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); }; -``` +```
    -Examples - -```js + Examples + + ```js httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### insertAfter @@ -3730,19 +3611,18 @@ Use `el.insertAdjacentHTML()` with a position of `'afterend'` to parse `htmlStri ```js const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString); -``` +```
    -Examples - -```js + Examples + + ```js insertAfter(document.getElementById('myId'), '

    after

    '); //
    ...

    after

    ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### insertBefore @@ -3752,19 +3632,18 @@ Use `el.insertAdjacentHTML()` with a position of `'beforebegin'` to parse `htmlS ```js const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString); -``` +```
    -Examples - -```js + Examples + + ```js insertBefore(document.getElementById('myId'), '

    before

    '); //

    before

    ...
    ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isBrowserTabFocused @@ -3774,19 +3653,18 @@ Use the `Document.hidden` property, introduced by the Page Visibility API to che ```js const isBrowserTabFocused = () => !document.hidden; -``` +```
    -Examples - -```js + Examples + + ```js isBrowserTabFocused(); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### nodeListToArray @@ -3796,19 +3674,18 @@ Use spread operator inside new array to convert a `NodeList` to an array. ```js const nodeListToArray = nodeList => [...nodeList]; -``` +```
    -Examples - -```js + Examples + + ```js nodeListToArray(document.childNodes); // [ , html ] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### observeMutations ![advanced](/advanced.svg) @@ -3837,20 +3714,19 @@ const observeMutations = (element, callback, options) => { ); return observer; }; -``` +```
    -Examples - -```js + Examples + + ```js const obs = observeMutations(document, console.log); // Logs all mutations that happen on the page obs.disconnect(); // Disconnects the observer and stops logging mutations on the page ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### off @@ -3861,21 +3737,20 @@ Omit the fourth argument `opts` to use `false` or specify it based on the option ```js const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); -``` +```
    -Examples - -```js + Examples + + ```js const fn = () => console.log('!'); document.body.addEventListener('click', fn); off(document.body, 'click', fn); // no longer logs '!' upon clicking on the page ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### on @@ -3891,12 +3766,12 @@ const on = (el, evt, fn, opts = {}) => { el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false); if (opts.target) return delegatorFn; }; -``` +```
    -Examples - -```js + Examples + + ```js const fn = () => console.log('!'); on(document.body, 'click', fn); // logs '!' upon clicking the body on(document.body, 'click', fn, { target: 'p' }); // logs '!' upon clicking a `p` element child of the body @@ -3904,9 +3779,8 @@ on(document.body, 'click', fn, { options: true }); // use capturing instead of b ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### onUserInputChange ![advanced](/advanced.svg) @@ -3931,21 +3805,20 @@ const onUserInputChange = callback => { (type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler); }); }; -``` +```
    -Examples - -```js + Examples + + ```js onUserInputChange(type => { console.log('The user is now using', type, 'as an input method.'); }); ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### prefix @@ -3963,19 +3836,18 @@ const prefix = prop => { ); return i !== -1 ? (i === 0 ? prop : prefixes[i] + capitalizedProp) : null; }; -``` +```
    -Examples - -```js + Examples + + ```js prefix('appearance'); // 'appearance' on a supported browser, otherwise 'webkitAppearance', 'mozAppearance', 'msAppearance' or 'oAppearance' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### recordAnimationFrames @@ -4007,12 +3879,12 @@ const recordAnimationFrames = (callback, autoStart = true) => { if (autoStart) start(); return { start, stop }; }; -``` +```
    -Examples - -```js + Examples + + ```js const cb = () => console.log('Animation frame fired'); const recorder = recordAnimationFrames(cb); // logs 'Animation frame fired' on each animation frame recorder.stop(); // stops logging @@ -4021,9 +3893,8 @@ const recorder2 = recordAnimationFrames(cb, false); // `start` needs to be expli ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### redirect @@ -4035,19 +3906,18 @@ Pass a second argument to simulate a link click (`true` - default) or an HTTP re ```js const redirect = (url, asLink = true) => asLink ? (window.location.href = url) : window.location.replace(url); -``` +```
    -Examples - -```js + Examples + + ```js redirect('https://google.com'); ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### runAsync ![advanced](/advanced.svg) @@ -4073,12 +3943,12 @@ const runAsync = fn => { }; }); }; -``` +```
    -Examples - -```js + Examples + + ```js const longRunningFunction = () => { let result = 0; for (let i = 0; i < 1000; i++) { @@ -4102,9 +3972,8 @@ runAsync(() => typeof outsideVariable).then(console.log); // 'undefined' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### scrollToTop @@ -4121,19 +3990,18 @@ const scrollToTop = () => { window.scrollTo(0, c - c / 8); } }; -``` +```
    -Examples - -```js + Examples + + ```js scrollToTop(); ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### setStyle @@ -4143,19 +4011,18 @@ Use `element.style` to set the value of the CSS rule for the specified element t ```js const setStyle = (el, ruleName, val) => (el.style[ruleName] = val); -``` +```
    -Examples - -```js + Examples + + ```js setStyle(document.querySelector('p'), 'font-size', '20px'); // The first

    element on the page will have a font-size of 20px ```

    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### show @@ -4165,19 +4032,18 @@ Use the spread operator (`...`) and `Array.forEach()` to clear the `display` pro ```js const show = (...el) => [...el].forEach(e => (e.style.display = '')); -``` +```
    -Examples - -```js + Examples + + ```js show(...document.querySelectorAll('img')); // Shows all elements on the page ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### smoothScroll @@ -4191,20 +4057,19 @@ const smoothScroll = element => document.querySelector(element).scrollIntoView({ behavior: 'smooth' }); -``` +```
    -Examples - -```js + Examples + + ```js smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar smoothScroll('.fooBar'); // scrolls smoothly to the first element with a class of fooBar ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### toggleClass @@ -4214,19 +4079,18 @@ Use `element.classList.toggle()` to toggle the specified class for the element. ```js const toggleClass = (el, className) => el.classList.toggle(className); -``` +```
    -Examples - -```js + Examples + + ```js toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymore ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### triggerEvent @@ -4239,20 +4103,19 @@ Omit the third argument, `detail`, if you do not want to pass custom data to the ```js const triggerEvent = (el, eventType, detail = undefined) => el.dispatchEvent(new CustomEvent(eventType, { detail: detail })); -``` +```
    -Examples - -```js + Examples + + ```js triggerEvent(document.getElementById('myId'), 'click'); triggerEvent(document.getElementById('myId'), 'click', { username: 'bob' }); ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### UUIDGeneratorBrowser @@ -4265,23 +4128,22 @@ const UUIDGeneratorBrowser = () => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16) ); -``` +```
    -Examples - -```js + Examples + + ```js UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d' ```
    + +[⬆ Back to top](#table-of-contents) -
    [⬆ Back to top](#table-of-contents) - ---- - ## ⏱️ Date - -### formatDuration + +--- +## ⏱️ Date### formatDuration Returns the human readable format of the given number of milliseconds. @@ -4305,20 +4167,19 @@ const formatDuration = ms => { .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`) .join(', '); }; -``` +```
    -Examples - -```js + Examples + + ```js formatDuration(1001); // '1 second, 1 millisecond' formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### getColonTimeFromDate @@ -4328,19 +4189,18 @@ Use `Date.toString()` and `String.slice()` to get the `HH:MM:SS` part of a given ```js const getColonTimeFromDate = date => date.toTimeString().slice(0, 8); -``` +```
    -Examples - -```js + Examples + + ```js getColonTimeFromDate(new Date()); // "08:38:00" ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### getDaysDiffBetweenDates @@ -4351,19 +4211,18 @@ Calculate the difference (in days) between two `Date` objects. ```js const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); -``` +```
    -Examples - -```js + Examples + + ```js getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### getMeridiemSuffixOfInteger @@ -4380,12 +4239,12 @@ const getMeridiemSuffixOfInteger = num => : num < 12 ? (num % 12) + 'am' : (num % 12) + 'pm'; -``` +```
    -Examples - -```js + Examples + + ```js getMeridiemSuffixOfInteger(0); // "12am" getMeridiemSuffixOfInteger(11); // "11am" getMeridiemSuffixOfInteger(13); // "1pm" @@ -4393,9 +4252,8 @@ getMeridiemSuffixOfInteger(25); // "1pm" ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### tomorrow @@ -4411,24 +4269,23 @@ const tomorrow = (long = false) => { ).padStart(2, '0')}`; return !long ? ret : `${ret}T00:00:00`; }; -``` +```
    -Examples - -```js + Examples + + ```js tomorrow(); // 2017-12-27 (if current date is 2017-12-26) tomorrow(true); // 2017-12-27T00:00:00 (if current date is 2017-12-26) ```
    + +[⬆ Back to top](#table-of-contents) -
    [⬆ Back to top](#table-of-contents) - ---- - ## πŸŽ›οΈ Function - -### attempt + +--- +## πŸŽ›οΈ Function### attempt Attempts to invoke a function with the provided arguments, returning either the result or the caught error object. @@ -4442,12 +4299,12 @@ const attempt = (fn, ...args) => { return e instanceof Error ? e : new Error(e); } }; -``` +```
    -Examples - -```js + Examples + + ```js var elements = attempt(function(selector) { return document.querySelectorAll(selector); }, '>_>'); @@ -4455,9 +4312,8 @@ if (elements instanceof Error) elements = []; // elements = [] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### bind @@ -4468,12 +4324,12 @@ Use `Array.concat()` to prepend any additional supplied parameters to the argume ```js const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]); -``` +```
    -Examples - -```js + Examples + + ```js function greet(greeting, punctuation) { return greeting + ' ' + this.user + punctuation; } @@ -4483,9 +4339,8 @@ console.log(freddyBound('hi', '!')); // 'hi fred!' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### bindKey @@ -4497,12 +4352,12 @@ Use the spread operator (`...`) to prepend any additional supplied parameters to ```js const bindKey = (context, fn, ...boundArgs) => (...args) => context[fn].apply(context, [...boundArgs, ...args]); -``` +```
    -Examples - -```js + Examples + + ```js const freddy = { user: 'fred', greet: function(greeting, punctuation) { @@ -4514,9 +4369,8 @@ console.log(freddyBound('hi', '!')); // 'hi fred!' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### chainAsync @@ -4530,12 +4384,12 @@ const chainAsync = fns => { const next = () => fns[curr++](next); next(); }; -``` +```
    -Examples - -```js + Examples + + ```js chainAsync([ next => { console.log('0 seconds'); @@ -4548,9 +4402,8 @@ chainAsync([ ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### compose @@ -4561,12 +4414,12 @@ The last (rightmost) function can accept one or more arguments; the remaining fu ```js const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); -``` +```
    -Examples - -```js + Examples + + ```js const add5 = x => x + 5; const multiply = (x, y) => x * y; const multiplyAndAdd5 = compose( @@ -4577,9 +4430,8 @@ multiplyAndAdd5(5, 2); // 15 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### composeRight @@ -4590,12 +4442,12 @@ The first (leftmost) function can accept one or more arguments; the remaining fu ```js const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); -``` +```
    -Examples - -```js + Examples + + ```js const add = (x, y) => x + y; const square = x => x * x; const addAndSquare = composeRight(add, square); @@ -4603,9 +4455,8 @@ addAndSquare(1, 2); // 9 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### converge @@ -4616,12 +4467,12 @@ Use the spread operator (`...`) to call `coverger` with the results of all other ```js const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args))); -``` +```
    -Examples - -```js + Examples + + ```js const average = converge((a, b) => a / b, [ arr => arr.reduce((a, v) => a + v, 0), arr => arr.length @@ -4630,9 +4481,8 @@ average([1, 2, 3, 4, 5, 6, 7]); // 4 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### curry @@ -4646,20 +4496,19 @@ If you want to curry a function that accepts a variable number of arguments (a v ```js const curry = (fn, arity = fn.length, ...args) => arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args); -``` +```
    -Examples - -```js + Examples + + ```js curry(Math.pow)(2)(10); // 1024 curry(Math.min, 3)(10)(50)(2); // 2 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### debounce @@ -4676,12 +4525,12 @@ const debounce = (fn, ms = 0) => { timeoutId = setTimeout(() => fn.apply(this, args), ms); }; }; -``` +```
    -Examples - -```js + Examples + + ```js window.addEventListener( 'resize', debounce(() => { @@ -4692,9 +4541,8 @@ window.addEventListener( ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### defer @@ -4704,12 +4552,12 @@ Use `setTimeout()` with a timeout of 1ms to add a new event to the browser event ```js const defer = (fn, ...args) => setTimeout(fn, 1, ...args); -``` +```
    -Examples - -```js + Examples + + ```js // Example A: defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a' @@ -4720,9 +4568,8 @@ defer(longRunningFunction); // Browser will update the HTML then run the functio ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### delay @@ -4733,12 +4580,12 @@ Use the spread (`...`) operator to supply the function with an arbitrary number ```js const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args); -``` +```
    -Examples - -```js + Examples + + ```js delay( function(text) { console.log(text); @@ -4749,9 +4596,8 @@ delay( ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### functionName @@ -4761,19 +4607,18 @@ Use `console.debug()` and the `name` property of the passed method to log the me ```js const functionName = fn => (console.debug(fn.name), fn); -``` +```
    -Examples - -```js + Examples + + ```js functionName(Math.max); // max (logged in debug channel of console) ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### hz @@ -4790,12 +4635,12 @@ const hz = (fn, iterations = 100) => { for (let i = 0; i < iterations; i++) fn(); return (1000 * iterations) / (performance.now() - before); }; -``` +```
    -Examples - -```js + Examples + + ```js // 10,000 element array const numbers = Array(10000) .fill() @@ -4815,9 +4660,8 @@ Math.round(hz(sumForLoop)); // 4784 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### memoize ![advanced](/advanced.svg) @@ -4836,12 +4680,12 @@ const memoize = fn => { cached.cache = cache; return cached; }; -``` +```
    -Examples - -```js + Examples + + ```js // See the `anagrams` snippet. const anagramsCached = memoize(anagrams); anagramsCached('javascript'); // takes a long time @@ -4850,9 +4694,8 @@ console.log(anagramsCached.cache); // The cached anagrams map ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### negate @@ -4862,19 +4705,18 @@ Take a predicate function and apply the not operator (`!`) to it with its argume ```js const negate = func => (...args) => !func(...args); -``` +```
    -Examples - -```js + Examples + + ```js [1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### once @@ -4892,12 +4734,12 @@ const once = fn => { return fn.apply(this, args); }; }; -``` +```
    -Examples - -```js + Examples + + ```js const startApp = function(event) { console.log(this, event); // document.body, MouseEvent }; @@ -4905,9 +4747,8 @@ document.body.addEventListener('click', once(startApp)); // only runs `startApp` ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### partial @@ -4917,21 +4758,20 @@ Use the spread operator (`...`) to prepend `partials` to the list of arguments o ```js const partial = (fn, ...partials) => (...args) => fn(...partials, ...args); -``` +```
    -Examples - -```js + Examples + + ```js const greet = (greeting, name) => greeting + ' ' + name + '!'; const greetHello = partial(greet, 'Hello'); greetHello('John'); // 'Hello John!' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### partialRight @@ -4941,21 +4781,20 @@ Use the spread operator (`...`) to append `partials` to the list of arguments of ```js const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials); -``` +```
    -Examples - -```js + Examples + + ```js const greet = (greeting, name) => greeting + ' ' + name + '!'; const greetJohn = partialRight(greet, 'John'); greetJohn('Hello'); // 'Hello John!' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### runPromisesInSeries @@ -4965,20 +4804,19 @@ Use `Array.reduce()` to create a promise chain, where each promise returns the n ```js const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); -``` +```
    -Examples - -```js + 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) - + +[⬆ Back to top](#table-of-contents) ### sleep @@ -4988,12 +4826,12 @@ Delay executing part of an `async` function, by putting it to sleep, returning a ```js const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); -``` +```
    -Examples - -```js + Examples + + ```js async function sleepyWork() { console.log("I'm going to sleep for 1 second."); await sleep(1000); @@ -5002,9 +4840,8 @@ async function sleepyWork() { ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### throttle ![advanced](/advanced.svg) @@ -5036,12 +4873,12 @@ const throttle = (fn, wait) => { } }; }; -``` +```
    -Examples - -```js + Examples + + ```js window.addEventListener( 'resize', throttle(function(evt) { @@ -5052,9 +4889,8 @@ window.addEventListener( ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### times @@ -5068,21 +4904,20 @@ const times = (n, fn, context = undefined) => { let i = 0; while (fn.call(context, i) !== false && ++i < n) {} }; -``` +```
    -Examples - -```js + Examples + + ```js var output = ''; times(5, i => (output += i)); console.log(output); // 01234 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### uncurry @@ -5100,21 +4935,20 @@ const uncurry = (fn, n = 1) => (...args) => { if (n > args.length) throw new RangeError('Arguments too few!'); return next(fn)(args.slice(0, n)); }; -``` +```
    -Examples - -```js + Examples + + ```js const add = x => y => z => x + y + z; const uncurriedAdd = uncurry(add, 3); uncurriedAdd(1, 2, 3); // 6 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### unfold @@ -5130,20 +4964,19 @@ const unfold = (fn, seed) => { while ((val = fn(val[1]))) result.push(val[0]); return result; }; -``` +```
    -Examples - -```js + Examples + + ```js var f = n => (n > 50 ? false : [-n, n + 10]); unfold(f, 10); // [-10, -20, -30, -40, -50] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### when @@ -5153,25 +4986,24 @@ Return a function expecting a single value, `x`, that returns the appropriate va ```js const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x); -``` +```
    -Examples - -```js + Examples + + ```js const doubleEvenNumbers = when(x => x % 2 === 0, x => x * 2); doubleEvenNumbers(2); // 4 doubleEvenNumbers(1); // 1 ```
    + +[⬆ Back to top](#table-of-contents) -
    [⬆ Back to top](#table-of-contents) - ---- - ## βž— Math - -### approximatelyEqual + +--- +## βž— Math### approximatelyEqual Checks if two numbers are approximately equal to each other. @@ -5180,19 +5012,18 @@ Omit the third parameter, `epsilon`, to use a default value of `0.001`. ```js const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon; -``` +```
    -Examples - -```js + Examples + + ```js approximatelyEqual(Math.PI / 2.0, 1.5708); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### average @@ -5202,20 +5033,19 @@ Use `Array.reduce()` to add each value to an accumulator, initialized with a val ```js const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length; -``` +```
    -Examples - -```js + Examples + + ```js average(...[1, 2, 3]); // 2 average(1, 2, 3); // 2 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### averageBy @@ -5227,20 +5057,19 @@ Use `Array.map()` to map each element to the value returned by `fn`, `Array.redu const averageBy = (arr, fn) => arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) / arr.length; -``` +```
    -Examples - -```js + Examples + + ```js averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5 averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### binomialCoefficient @@ -5263,19 +5092,18 @@ const binomialCoefficient = (n, k) => { for (let j = 2; j <= k; j++) res *= (n - j + 1) / j; return Math.round(res); }; -``` +```
    -Examples - -```js + Examples + + ```js binomialCoefficient(8, 2); // 28 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### clampNumber @@ -5286,20 +5114,19 @@ Otherwise, return the nearest number in the range. ```js const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); -``` +```
    -Examples - -```js + Examples + + ```js clampNumber(2, 3, 5); // 3 clampNumber(1, -1, -5); // -1 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### degreesToRads @@ -5309,19 +5136,18 @@ Use `Math.PI` and the degree to radian formula to convert the angle from degrees ```js const degreesToRads = deg => (deg * Math.PI) / 180.0; -``` +```
    -Examples - -```js + Examples + + ```js degreesToRads(90.0); // ~1.5708 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### digitize @@ -5332,19 +5158,18 @@ Use `Array.map()` and `parseInt()` to transform each value to an integer. ```js const digitize = n => [...`${n}`].map(i => parseInt(i)); -``` +```
    -Examples - -```js + Examples + + ```js digitize(123); // [1, 2, 3] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### distance @@ -5354,19 +5179,18 @@ Use `Math.hypot()` to calculate the Euclidean distance between two points. ```js const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); -``` +```
    -Examples - -```js + Examples + + ```js distance(1, 1, 2, 3); // 2.23606797749979 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### elo ![advanced](/advanced.svg) @@ -5397,12 +5221,12 @@ const elo = ([...ratings], kFactor = 32, selfRating) => { } return ratings; }; -``` +```
    -Examples - -```js + Examples + + ```js // Standard 1v1s elo([1200, 1200]); // [1216, 1184] elo([1200, 1200], 64); // [1232, 1168] @@ -5416,9 +5240,8 @@ own individual rating by supplying it as the third argument. ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### factorial @@ -5438,19 +5261,18 @@ const factorial = n => : n <= 1 ? 1 : n * factorial(n - 1); -``` +```
    -Examples - -```js + Examples + + ```js factorial(6); // 720 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### fibonacci @@ -5465,19 +5287,18 @@ const fibonacci = n => (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), [] ); -``` +```
    -Examples - -```js + Examples + + ```js fibonacci(6); // [0, 1, 1, 2, 3, 5] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### gcd @@ -5492,20 +5313,19 @@ const gcd = (...arr) => { const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); return [...arr].reduce((a, b) => _gcd(a, b)); }; -``` +```
    -Examples - -```js + Examples + + ```js gcd(8, 36); // 4 gcd(...[12, 8, 32]); // 4 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### geometricProgression @@ -5521,21 +5341,20 @@ const geometricProgression = (end, start = 1, step = 2) => Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map( (v, i) => start * step ** i ); -``` +```
    -Examples - -```js + Examples + + ```js geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256] geometricProgression(256, 3); // [3, 6, 12, 24, 48, 96, 192] geometricProgression(256, 1, 4); // [1, 4, 16, 64, 256] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### hammingDistance @@ -5546,19 +5365,18 @@ Count and return the number of `1`s in the string, using `match(/1/g)`. ```js const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length; -``` +```
    -Examples - -```js + Examples + + ```js hammingDistance(2, 3); // 1 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### inRange @@ -5572,12 +5390,12 @@ const inRange = (n, start, end = null) => { if (end && start > end) [end, start] = [start, end]; return end == null ? n >= 0 && n < start : n >= start && n < end; }; -``` +```
    -Examples - -```js + Examples + + ```js inRange(3, 2, 5); // true inRange(3, 4); // true inRange(2, 3, 5); // false @@ -5585,9 +5403,8 @@ inRange(3, 2); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isDivisible @@ -5597,19 +5414,18 @@ Use the modulo operator (`%`) to check if the remainder is equal to `0`. ```js const isDivisible = (dividend, divisor) => dividend % divisor === 0; -``` +```
    -Examples - -```js + Examples + + ```js isDivisible(6, 3); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isEven @@ -5620,19 +5436,18 @@ Returns `true` if the number is even, `false` if the number is odd. ```js const isEven = num => num % 2 === 0; -``` +```
    -Examples - -```js + Examples + + ```js isEven(3); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isPrime @@ -5647,19 +5462,18 @@ const isPrime = num => { for (var i = 2; i <= boundary; i++) if (num % i === 0) return false; return num >= 2; }; -``` +```
    -Examples - -```js + Examples + + ```js isPrime(11); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### lcm @@ -5674,20 +5488,19 @@ const lcm = (...arr) => { const _lcm = (x, y) => (x * y) / gcd(x, y); return [...arr].reduce((a, b) => _lcm(a, b)); }; -``` +```
    -Examples - -```js + Examples + + ```js lcm(12, 7); // 84 lcm(...[1, 3, 4, 5]); // 60 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### luhnCheck ![advanced](/advanced.svg) @@ -5710,21 +5523,20 @@ const luhnCheck = num => { sum += lastDigit; return sum % 10 === 0; }; -``` +```
    -Examples - -```js + Examples + + ```js luhnCheck('4485275742308327'); // true luhnCheck(6011329933655299); // false luhnCheck(123456789); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### maxBy @@ -5734,20 +5546,19 @@ Use `Array.map()` to map each element to the value returned by `fn`, `Math.max() ```js const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); -``` +```
    -Examples - -```js + Examples + + ```js maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8 maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### median @@ -5762,19 +5573,18 @@ const median = arr => { nums = [...arr].sort((a, b) => a - b); return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; }; -``` +```
    -Examples - -```js + Examples + + ```js median([5, 6, 50, 1, -5]); // 5 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### minBy @@ -5784,20 +5594,19 @@ Use `Array.map()` to map each element to the value returned by `fn`, `Math.min() ```js const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); -``` +```
    -Examples - -```js + Examples + + ```js minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 2 minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 2 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### percentile @@ -5808,19 +5617,18 @@ Use `Array.reduce()` to calculate how many numbers are below the value and how m ```js const percentile = (arr, val) => (100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0)) / arr.length; -``` +```
    -Examples - -```js + Examples + + ```js percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6); // 55 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### powerset @@ -5830,19 +5638,18 @@ Use `Array.reduce()` combined with `Array.map()` to iterate over elements and co ```js const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); -``` +```
    -Examples - -```js + Examples + + ```js powerset([1, 2]); // [[], [1], [2], [2,1]] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### primes @@ -5858,19 +5665,18 @@ const primes = num => { numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x))); return arr; }; -``` +```
    -Examples - -```js + Examples + + ```js primes(10); // [2,3,5,7] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### radsToDegrees @@ -5880,19 +5686,18 @@ Use `Math.PI` and the radian to degree formula to convert the angle from radians ```js const radsToDegrees = rad => (rad * 180.0) / Math.PI; -``` +```
    -Examples - -```js + Examples + + ```js radsToDegrees(Math.PI / 2); // 90 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### randomIntArrayInRange @@ -5903,19 +5708,18 @@ Use `Array.from()` to create an empty array of the specific length, `Math.random ```js const randomIntArrayInRange = (min, max, n = 1) => Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); -``` +```
    -Examples - -```js + Examples + + ```js randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### randomIntegerInRange @@ -5925,19 +5729,18 @@ Use `Math.random()` to generate a random number and map it to the desired range, ```js const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; -``` +```
    -Examples - -```js + Examples + + ```js randomIntegerInRange(0, 5); // 2 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### randomNumberInRange @@ -5947,19 +5750,18 @@ Use `Math.random()` to generate a random value, map it to the desired range usin ```js const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; -``` +```
    -Examples - -```js + Examples + + ```js randomNumberInRange(2, 10); // 6.0211363285087005 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### round @@ -5970,19 +5772,18 @@ Omit the second argument, `decimals` to round to an integer. ```js const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); -``` +```
    -Examples - -```js + Examples + + ```js round(1.005, 2); // 1.01 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### sdbm @@ -5999,19 +5800,18 @@ const sdbm = str => { 0 ); }; -``` +```
    -Examples - -```js + Examples + + ```js sdbm('name'); // -3521204949 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### standardDeviation @@ -6029,20 +5829,19 @@ const standardDeviation = (arr, usePopulation = false) => { (arr.length - (usePopulation ? 0 : 1)) ); }; -``` +```
    -Examples - -```js + 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) - + +[⬆ Back to top](#table-of-contents) ### sum @@ -6052,19 +5851,18 @@ Use `Array.reduce()` to add each value to an accumulator, initialized with a val ```js const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); -``` +```
    -Examples - -```js + Examples + + ```js sum(...[1, 2, 3, 4]); // 10 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### sumBy @@ -6075,20 +5873,19 @@ Use `Array.map()` to map each element to the value returned by `fn`, `Array.redu ```js const sumBy = (arr, fn) => arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0); -``` +```
    -Examples - -```js + Examples + + ```js sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 20 sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 20 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### sumPower @@ -6104,21 +5901,20 @@ const sumPower = (end, power = 2, start = 1) => .fill(0) .map((x, i) => (i + start) ** power) .reduce((a, b) => a + b, 0); -``` +```
    -Examples - -```js + Examples + + ```js sumPower(10); // 385 sumPower(10, 3); //3025 sumPower(10, 3, 5); //2925 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### toSafeInteger @@ -6130,24 +5926,23 @@ Use `Math.round()` to convert to an integer. ```js const toSafeInteger = num => Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)); -``` +```
    -Examples - -```js + Examples + + ```js toSafeInteger('3.2'); // 3 toSafeInteger(Infinity); // 9007199254740991 ```
    + +[⬆ Back to top](#table-of-contents) -
    [⬆ Back to top](#table-of-contents) - ---- - ## πŸ“¦ Node - -### atob + +--- +## πŸ“¦ Node### atob Decodes a string of data which has been encoded using base-64 encoding. @@ -6155,19 +5950,18 @@ Create a `Buffer` for the given string with base-64 encoding and use `Buffer.toS ```js const atob = str => new Buffer(str, 'base64').toString('binary'); -``` +```
    -Examples - -```js + Examples + + ```js atob('Zm9vYmFy'); // 'foobar' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### btoa @@ -6177,19 +5971,18 @@ Create a `Buffer` for the given string with binary encoding and use `Buffer.toSt ```js const btoa = str => new Buffer(str, 'binary').toString('base64'); -``` +```
    -Examples - -```js + Examples + + ```js btoa('foobar'); // 'Zm9vYmFy' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### colorize @@ -6217,21 +6010,20 @@ const colorize = (...args) => ({ bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`, bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m` }); -``` +```
    -Examples - -```js + Examples + + ```js console.log(colorize('foo').red); // 'foo' (red letters) console.log(colorize('foo', 'bar').bgBlue); // 'foo bar' (blue background) console.log(colorize(colorize('foo').yellow, colorize('foo').green).bgWhite); // 'foo bar' (first word in yellow letters, second word in green letters, white background for both) ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### hasFlags @@ -6243,12 +6035,12 @@ Use a regular expression to test if the specified flags are prefixed with `-` or ```js const hasFlags = (...flags) => flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag)); -``` +```
    -Examples - -```js + Examples + + ```js // node myScript.js -s --test --cool=true hasFlags('-s'); // true hasFlags('--test', 'cool=true', '-s'); // true @@ -6256,9 +6048,8 @@ hasFlags('special'); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### hashNode @@ -6281,19 +6072,18 @@ const hashNode = val => 0 ) ); -``` +```
    -Examples - -```js + Examples + + ```js hashNode(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isTravisCI @@ -6303,19 +6093,18 @@ Checks if the current environment has the `TRAVIS` and `CI` environment variable ```js const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; -``` +```
    -Examples - -```js + Examples + + ```js isTravisCI(); // true (if code is running on Travis CI) ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### JSONToFile @@ -6327,19 +6116,18 @@ Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` const fs = require('fs'); const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); -``` +```
    -Examples - -```js + Examples + + ```js JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### readFileLines @@ -6356,12 +6144,12 @@ const readFileLines = filename => .readFileSync(filename) .toString('UTF8') .split('\n'); -``` +```
    -Examples - -```js + Examples + + ```js /* contents of test.txt : line1 @@ -6375,9 +6163,8 @@ console.log(arr); // ['line1', 'line2', 'line3']
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### untildify @@ -6387,19 +6174,18 @@ Use `String.replace()` with a regular expression and `OS.homedir()` to replace t ```js const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`); -``` +```
    -Examples - -```js + Examples + + ```js untildify('~/node'); // '/Users/aUser/node' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### UUIDGeneratorNode @@ -6413,23 +6199,22 @@ const UUIDGeneratorNode = () => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16) ); -``` +```
    -Examples - -```js + Examples + + ```js UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc' ```
    + +[⬆ Back to top](#table-of-contents) -
    [⬆ Back to top](#table-of-contents) - ---- - ## πŸ—ƒοΈ Object - -### bindAll + +--- +## πŸ—ƒοΈ Object### bindAll Binds methods of an object to the object itself, overwriting the existing method. @@ -6445,12 +6230,12 @@ const bindAll = (obj, ...fns) => }) ) ); -``` +```
    -Examples - -```js + Examples + + ```js var view = { label: 'docs', click: function() { @@ -6462,9 +6247,8 @@ jQuery(element).on('click', view.click); // Logs 'clicked docs' when clicked. ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### deepClone @@ -6482,20 +6266,19 @@ const deepClone = obj => { ); return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone; }; -``` +```
    -Examples - -```js + Examples + + ```js const a = { foo: 'bar', obj: { a: 1, b: 2 } }; const b = deepClone(a); // a !== b, a.obj !== b.obj ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### deepFreeze @@ -6509,12 +6292,12 @@ const deepFreeze = obj => prop => !obj[prop] instanceof Object || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop]) ) || Object.freeze(obj); -``` +```
    -Examples - -```js + Examples + + ```js 'use strict'; const o = deepFreeze([1, [2, 3]]); @@ -6524,9 +6307,8 @@ o[1][0] = 4; // not allowed as well ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### defaults @@ -6536,19 +6318,18 @@ Use `Object.assign()` to create a new empty object and copy the original one to ```js const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); -``` +```
    -Examples - -```js + Examples + + ```js defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 } ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### dig @@ -6565,12 +6346,12 @@ const dig = (obj, target) => if (acc !== undefined) return acc; if (typeof val === 'object') return dig(val, target); }, undefined); -``` +```
    -Examples - -```js + Examples + + ```js const data = { level1: { level2: { @@ -6583,9 +6364,8 @@ dig(data, 'level4'); // undefined ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### equals ![advanced](/advanced.svg) @@ -6606,19 +6386,18 @@ const equals = (a, b) => { if (keys.length !== Object.keys(b).length) return false; return keys.every(k => equals(a[k], b[k])); }; -``` +```
    -Examples - -```js + Examples + + ```js equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### findKey @@ -6628,12 +6407,12 @@ Use `Object.keys(obj)` to get all the properties of the object, `Array.find()` t ```js const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj)); -``` +```
    -Examples - -```js + Examples + + ```js findKey( { barney: { age: 36, active: true }, @@ -6645,9 +6424,8 @@ findKey( ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### findLastKey @@ -6660,12 +6438,12 @@ const findLastKey = (obj, fn) => Object.keys(obj) .reverse() .find(key => fn(obj[key], key, obj)); -``` +```
    -Examples - -```js + Examples + + ```js findLastKey( { barney: { age: 36, active: true }, @@ -6677,9 +6455,8 @@ findLastKey( ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### flattenObject @@ -6699,19 +6476,18 @@ const flattenObject = (obj, prefix = '') => else acc[pre + k] = obj[k]; return acc; }, {}); -``` +```
    -Examples - -```js + Examples + + ```js flattenObject({ a: { b: { c: 1 } }, d: 1 }); // { 'a.b.c': 1, d: 1 } ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### forOwn @@ -6721,19 +6497,18 @@ Use `Object.keys(obj)` to get all the properties of the object, `Array.forEach() ```js const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj)); -``` +```
    -Examples - -```js + Examples + + ```js forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### forOwnRight @@ -6746,19 +6521,18 @@ const forOwnRight = (obj, fn) => Object.keys(obj) .reverse() .forEach(key => fn(obj[key], key, obj)); -``` +```
    -Examples - -```js + Examples + + ```js forOwnRight({ foo: 'bar', a: 1 }, v => console.log(v)); // 1, 'bar' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### functions @@ -6775,12 +6549,12 @@ const functions = (obj, inherited = false) => ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))] : Object.keys(obj) ).filter(key => typeof obj[key] === 'function'); -``` +```
    -Examples - -```js + Examples + + ```js function Foo() { this.a = () => 1; this.b = () => 2; @@ -6791,9 +6565,8 @@ functions(new Foo(), true); // ['a', 'b', 'c'] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### get @@ -6810,20 +6583,19 @@ const get = (from, ...selectors) => .filter(t => t !== '') .reduce((prev, cur) => prev && prev[cur], from) ); -``` +```
    -Examples - -```js + Examples + + ```js const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] }; get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ['val to select', 1, 'test'] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### invertKeyValues @@ -6840,20 +6612,19 @@ const invertKeyValues = (obj, fn) => acc[val].push(key); return acc; }, {}); -``` +```
    -Examples - -```js + Examples + + ```js invertKeyValues({ a: 1, b: 2, c: 1 }); // { 1: [ 'a', 'c' ], 2: [ 'b' ] } invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value); // { group1: [ 'a', 'c' ], group2: [ 'b' ] } ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### lowercaseKeys @@ -6868,20 +6639,19 @@ const lowercaseKeys = obj => acc[key.toLowerCase()] = obj[key]; return acc; }, {}); -``` +```
    -Examples - -```js + Examples + + ```js const myObj = { Name: 'Adam', sUrnAME: 'Smith' }; const myObjLower = lowercaseKeys(myObj); // {name: 'Adam', surname: 'Smith'}; ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### mapKeys @@ -6896,19 +6666,18 @@ const mapKeys = (obj, fn) => acc[fn(obj[k], k, obj)] = obj[k]; return acc; }, {}); -``` +```
    -Examples - -```js + Examples + + ```js mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 } ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### mapValues @@ -6923,12 +6692,12 @@ const mapValues = (obj, fn) => acc[k] = fn(obj[k], k, obj); return acc; }, {}); -``` +```
    -Examples - -```js + Examples + + ```js const users = { fred: { user: 'fred', age: 40 }, pebbles: { user: 'pebbles', age: 1 } @@ -6937,9 +6706,8 @@ mapValues(users, u => u.age); // { fred: 40, pebbles: 1 } ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### matches @@ -6950,20 +6718,19 @@ Use `Object.keys(source)` to get all the keys of the second object, then `Array. ```js const matches = (obj, source) => Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]); -``` +```
    -Examples - -```js + Examples + + ```js matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // true matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### matchesWith @@ -6980,12 +6747,12 @@ const matchesWith = (obj, source, fn) => ? fn(obj[key], source[key], key, obj, source) : obj[key] == source[key] ); -``` +```
    -Examples - -```js + Examples + + ```js const isGreeting = val => /^h(?:i|ello)$/.test(val); matchesWith( { greeting: 'hello' }, @@ -6995,9 +6762,8 @@ matchesWith( ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### merge @@ -7016,12 +6782,12 @@ const merge = (...objs) => }, {}), {} ); -``` +```
    -Examples - -```js + Examples + + ```js const object = { a: [{ x: 2 }, { y: 4 }], b: 1 @@ -7035,9 +6801,8 @@ merge(object, other); // { a: [ { x: 2 }, { y: 4 }, { z: 3 } ], b: [ 1, 2, 3 ], ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### nest @@ -7054,12 +6819,12 @@ const nest = (items, id = null, link = 'parent_id') => items .filter(item => item[link] === id) .map(item => ({ ...item, children: nest(items, item.id) })); -``` +```
    -Examples - -```js + Examples + + ```js // One top level comment const comments = [ { id: 1, parent_id: null }, @@ -7073,9 +6838,8 @@ const nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### objectFromPairs @@ -7085,19 +6849,18 @@ Use `Array.reduce()` to create and combine key-value pairs. ```js const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {}); -``` +```
    -Examples - -```js + Examples + + ```js objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2} ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### objectToPairs @@ -7107,19 +6870,18 @@ Use `Object.keys()` and `Array.map()` to iterate over the object's keys and prod ```js const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); -``` +```
    -Examples - -```js + Examples + + ```js objectToPairs({ a: 1, b: 2 }); // [['a',1],['b',2]] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### omit @@ -7133,19 +6895,18 @@ const omit = (obj, arr) => Object.keys(obj) .filter(k => !arr.includes(k)) .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); -``` +```
    -Examples - -```js + Examples + + ```js omit({ a: 1, b: '2', c: 3 }, ['b']); // { 'a': 1, 'c': 3 } ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### omitBy @@ -7159,19 +6920,18 @@ const omitBy = (obj, fn) => Object.keys(obj) .filter(k => !fn(obj[k], k)) .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); -``` +```
    -Examples - -```js + Examples + + ```js omitBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { b: '2' } ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### orderBy @@ -7191,21 +6951,20 @@ const orderBy = (arr, props, orders) => return acc; }, 0) ); -``` +```
    -Examples - -```js + Examples + + ```js const users = [{ name: 'fred', age: 48 }, { name: 'barney', age: 36 }, { name: 'fred', age: 40 }]; orderBy(users, ['name', 'age'], ['asc', 'desc']); // [{name: 'barney', age: 36}, {name: 'fred', age: 48}, {name: 'fred', age: 40}] orderBy(users, ['name', 'age']); // [{name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### pick @@ -7216,19 +6975,18 @@ Use `Array.reduce()` to convert the filtered/picked keys back to an object with ```js const pick = (obj, arr) => arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); -``` +```
    -Examples - -```js + Examples + + ```js pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 } ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### pickBy @@ -7242,19 +7000,18 @@ const pickBy = (obj, fn) => Object.keys(obj) .filter(k => fn(obj[k], k)) .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); -``` +```
    -Examples - -```js + Examples + + ```js pickBy({ a: 1, b: '2', c: 3 }, x => typeof x === 'number'); // { 'a': 1, 'c': 3 } ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### renameKeys @@ -7271,20 +7028,19 @@ const renameKeys = (keysMap, obj) => }), {} ); -``` +```
    -Examples - -```js + Examples + + ```js const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 }; renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 } ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### shallowClone @@ -7294,20 +7050,19 @@ Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of th ```js const shallowClone = obj => Object.assign({}, obj); -``` +```
    -Examples - -```js + Examples + + ```js const a = { x: true, y: 1 }; const b = shallowClone(a); // a !== b ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### size @@ -7329,21 +7084,20 @@ const size = val => : typeof val === 'string' ? new Blob([val]).size : 0; -``` +```
    -Examples - -```js + Examples + + ```js size([1, 2, 3, 4, 5]); // 5 size('size'); // 4 size({ one: 1, two: 2, three: 3 }); // 3 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### transform @@ -7353,12 +7107,12 @@ Use `Object.keys(obj)` to iterate over each key in the object, `Array.reduce()` ```js const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc); -``` +```
    -Examples - -```js + Examples + + ```js transform( { a: 1, b: 2, c: 1 }, (r, v, k) => { @@ -7370,9 +7124,8 @@ transform( ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### truthCheckCollection @@ -7382,19 +7135,18 @@ Use `Array.every()` to check if each passed object has the specified property an ```js const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]); -``` +```
    -Examples - -```js + Examples + + ```js truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### unflattenObject ![advanced](/advanced.svg) @@ -7421,23 +7173,22 @@ const unflattenObject = obj => } else acc[k] = obj[k]; return acc; }, {}); -``` +```
    -Examples - -```js + Examples + + ```js unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 } ```
    + +[⬆ Back to top](#table-of-contents) -
    [⬆ Back to top](#table-of-contents) - ---- - ## πŸ“œ String - -### byteSize + +--- +## πŸ“œ String### byteSize Returns the length of a string in bytes. @@ -7445,20 +7196,19 @@ Convert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/ ```js const byteSize = str => new Blob([str]).size; -``` +```
    -Examples - -```js + Examples + + ```js byteSize('πŸ˜€'); // 4 byteSize('Hello World'); // 11 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### capitalize @@ -7470,20 +7220,19 @@ Omit the `lowerRest` parameter to keep the rest of the string intact, or set it ```js const capitalize = ([first, ...rest], lowerRest = false) => first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); -``` +```
    -Examples - -```js + Examples + + ```js capitalize('fooBar'); // 'FooBar' capitalize('fooBar', true); // 'Foobar' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### capitalizeEveryWord @@ -7493,19 +7242,18 @@ Use `String.replace()` to match the first character of each word and `String.toU ```js const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); -``` +```
    -Examples - -```js + Examples + + ```js capitalizeEveryWord('hello world!'); // 'Hello World!' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### CSVToArray @@ -7522,21 +7270,20 @@ const CSVToArray = (data, delimiter = ',', omitFirstRow = false) => .slice(omitFirstRow ? data.indexOf('\n') + 1 : 0) .split('\n') .map(v => v.split(delimiter)); -``` +```
    -Examples - -```js + Examples + + ```js CSVToArray('a,b\nc,d'); // [['a','b'],['c','d']]; CSVToArray('a;b\nc;d', ';'); // [['a','b'],['c','d']]; CSVToArray('col1,col2\na,b\nc,d', ',', true); // [['a','b'],['c','d']]; ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### CSVToJSON ![advanced](/advanced.svg) @@ -7559,20 +7306,19 @@ const CSVToJSON = (data, delimiter = ',') => { return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {}); }); }; -``` +```
    -Examples - -```js + Examples + + ```js CSVToJSON('col1,col2\na,b\nc,d'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}]; CSVToJSON('col1;col2\na;b\nc;d', ';'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}]; ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### decapitalize @@ -7584,20 +7330,19 @@ Omit the `upperRest` parameter to keep the rest of the string intact, or set it ```js const decapitalize = ([first, ...rest], upperRest = false) => first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join('')); -``` +```
    -Examples - -```js + Examples + + ```js decapitalize('FooBar'); // 'fooBar' decapitalize('FooBar', true); // 'fOOBAR' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### escapeHTML @@ -7618,19 +7363,18 @@ const escapeHTML = str => '"': '"' }[tag] || tag) ); -``` +```
    -Examples - -```js + Examples + + ```js escapeHTML('Me & you'); // '<a href="#">Me & you</a>' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### escapeRegExp @@ -7640,19 +7384,18 @@ Use `String.replace()` to escape special characters. ```js const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); -``` +```
    -Examples - -```js + Examples + + ```js escapeRegExp('(test)'); // \\(test\\) ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### fromCamelCase @@ -7667,21 +7410,20 @@ const fromCamelCase = (str, separator = '_') => .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2') .toLowerCase(); -``` +```
    -Examples - -```js + 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) - + +[⬆ Back to top](#table-of-contents) ### isAbsoluteURL @@ -7691,21 +7433,20 @@ Use a regular expression to test if the string is an absolute URL. ```js const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); -``` +```
    -Examples - -```js + Examples + + ```js isAbsoluteURL('https://google.com'); // true isAbsoluteURL('ftp://www.myserver.net'); // true isAbsoluteURL('/foo/bar'); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isAnagram @@ -7724,19 +7465,18 @@ const isAnagram = (str1, str2) => { .join(''); return normalize(str1) === normalize(str2); }; -``` +```
    -Examples - -```js + Examples + + ```js isAnagram('iceman', 'cinema'); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isLowerCase @@ -7746,21 +7486,20 @@ Convert the given string to lower case, using `String.toLowerCase()` and compare ```js const isLowerCase = str => str === str.toLowerCase(); -``` +```
    -Examples - -```js + Examples + + ```js isLowerCase('abc'); // true isLowerCase('a3@$'); // true isLowerCase('Ab4'); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isUpperCase @@ -7771,21 +7510,20 @@ Convert the given string to upper case, using `String.toUpperCase()` and compare ```js const isUpperCase = str => str === str.toUpperCase(); -``` +```
    -Examples - -```js + Examples + + ```js isUpperCase('ABC'); // true isLowerCase('A3@$'); // true isLowerCase('aB4'); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### mapString @@ -7801,19 +7539,18 @@ const mapString = (str, fn) => .split('') .map((c, i) => fn(c, i, str)) .join(''); -``` +```
    -Examples - -```js + Examples + + ```js mapString('lorem ipsum', c => c.toUpperCase()); // 'LOREM IPSUM' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### mask @@ -7827,21 +7564,20 @@ Omit the third argument, `mask`, to use a default character of `'*'` for the mas ```js const mask = (cc, num = 4, mask = '*') => ('' + cc).slice(0, -num).replace(/./g, mask) + ('' + cc).slice(-num); -``` +```
    -Examples - -```js + Examples + + ```js mask(1234567890); // '******7890' mask(1234567890, 3); // '*******890' mask(1234567890, -4, '$'); // '$$$$567890' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### pad @@ -7853,21 +7589,20 @@ Omit the third argument, `char`, to use the whitespace character as the default ```js const pad = (str, length, char = ' ') => str.padStart((str.length + length) / 2, char).padEnd(length, char); -``` +```
    -Examples - -```js + Examples + + ```js pad('cat', 8); // ' cat ' pad(String(42), 6, '0'); // '004200' pad('foobar', 3); // 'foobar' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### palindrome @@ -7881,19 +7616,18 @@ const palindrome = str => { const s = str.toLowerCase().replace(/[\W_]/g, ''); return s === [...s].reverse().join(''); }; -``` +```
    -Examples - -```js + Examples + + ```js palindrome('taco cat'); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### pluralize @@ -7908,12 +7642,12 @@ const pluralize = (val, word, plural = word + 's') => { if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]); return _pluralize(val, word, plural); }; -``` +```
    -Examples - -```js + Examples + + ```js pluralize(0, 'apple'); // 'apples' pluralize(1, 'apple'); // 'apple' pluralize(2, 'apple'); // 'apples' @@ -7928,9 +7662,8 @@ autoPluralize(2, 'person'); // 'people' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### removeNonASCII @@ -7940,19 +7673,18 @@ Use a regular expression to remove non-printable ASCII characters. ```js const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); -``` +```
    -Examples - -```js + Examples + + ```js removeNonASCII('ÀÄçÇéÉΓͺlorem-ipsumΓΆΓ–ΓΓΎΓΊΓš'); // 'lorem-ipsum' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### reverseString @@ -7963,19 +7695,18 @@ Combine characters to get a string using `String.join('')`. ```js const reverseString = str => [...str].reverse().join(''); -``` +```
    -Examples - -```js + Examples + + ```js reverseString('foobar'); // 'raboof' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### sortCharactersInString @@ -7985,19 +7716,18 @@ Use the spread operator (`...`), `Array.sort()` and `String.localeCompare()` to ```js const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join(''); -``` +```
    -Examples - -```js + Examples + + ```js sortCharactersInString('cabbage'); // 'aabbceg' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### splitLines @@ -8007,19 +7737,18 @@ Use `String.split()` and a regular expression to match line breaks and create an ```js const splitLines = str => str.split(/\r?\n/); -``` +```
    -Examples - -```js + Examples + + ```js splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , ''] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### stringPermutations ![advanced](/advanced.svg) @@ -8043,19 +7772,18 @@ const stringPermutations = str => { [] ); }; -``` +```
    -Examples - -```js + Examples + + ```js stringPermutations('abc'); // ['abc','acb','bac','bca','cab','cba'] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### stripHTMLTags @@ -8065,19 +7793,18 @@ Use a regular expression to remove HTML/XML tags from a string. ```js const stripHTMLTags = str => str.replace(/<[^>]*>/g, ''); -``` +```
    -Examples - -```js + Examples + + ```js stripHTMLTags('

    lorem ipsum

    '); // 'lorem ipsum' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### toCamelCase @@ -8095,12 +7822,12 @@ const toCamelCase = str => { .join(''); return s.slice(0, 1).toLowerCase() + s.slice(1); }; -``` +```
    -Examples - -```js + Examples + + ```js toCamelCase('some_database_field_name'); // 'someDatabaseFieldName' toCamelCase('Some label that needs to be camelized'); // 'someLabelThatNeedsToBeCamelized' toCamelCase('some-javascript-property'); // 'someJavascriptProperty' @@ -8108,9 +7835,8 @@ toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'someMi ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### toKebabCase @@ -8125,12 +7851,12 @@ const toKebabCase = 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()) .join('-'); -``` +```
    -Examples - -```js + Examples + + ```js toKebabCase('camelCase'); // 'camel-case' toKebabCase('some text'); // 'some-text' toKebabCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some-mixed-string-with-spaces-underscores-and-hyphens' @@ -8139,9 +7865,8 @@ toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSo ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### toSnakeCase @@ -8156,12 +7881,12 @@ const toSnakeCase = 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()) .join('_'); -``` +```
    -Examples - -```js + Examples + + ```js toSnakeCase('camelCase'); // 'camel_case' toSnakeCase('some text'); // 'some_text' toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some_mixed_string_with_spaces_underscores_and_hyphens' @@ -8170,9 +7895,8 @@ toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSo ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### truncateString @@ -8184,19 +7908,18 @@ Return the string truncated to the desired length, with `'...'` appended to the ```js const truncateString = (str, num) => str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; -``` +```
    -Examples - -```js + Examples + + ```js truncateString('boomerang', 7); // 'boom...' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### unescapeHTML @@ -8217,19 +7940,18 @@ const unescapeHTML = str => '"': '"' }[tag] || tag) ); -``` +```
    -Examples - -```js + Examples + + ```js unescapeHTML('<a href="#">Me & you</a>'); // 'Me & you' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### URLJoin ![advanced](/advanced.svg) @@ -8247,19 +7969,18 @@ const URLJoin = (...args) => .replace(/\/(\?|&|#[^!])/g, '$1') .replace(/\?/g, '&') .replace('&', '?'); -``` +```
    -Examples - -```js + Examples + + ```js URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); // 'http://www.google.com/a/b/cd?foo=123&bar=foo' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### words @@ -8270,24 +7991,23 @@ Omit the second argument to use the default regexp. ```js const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); -``` +```
    -Examples - -```js + Examples + + ```js words('I love javaScript!!'); // ["I", "love", "javaScript"] words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"] ```
    + +[⬆ Back to top](#table-of-contents) -
    [⬆ Back to top](#table-of-contents) - ---- - ## πŸ“ƒ Type - -### getType + +--- +## πŸ“ƒ Type### getType Returns the native type of a value. @@ -8296,19 +8016,18 @@ Returns lowercased constructor name of value, `"undefined"` or `"null"` if value ```js const getType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase(); -``` +```
    -Examples - -```js + Examples + + ```js getType(new Set([1, 2, 3])); // 'set' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### is @@ -8318,12 +8037,12 @@ Ensure the value is not `undefined` or `null` using `Array.includes()`, and comp ```js const is = (type, val) => ![, null].includes(val) && val.constructor === type; -``` +```
    -Examples - -```js + Examples + + ```js is(Array, [1]); // true is(ArrayBuffer, new ArrayBuffer()); // true is(Map, new Map()); // true @@ -8340,9 +8059,8 @@ is(Boolean, new Boolean(true)); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isArrayLike @@ -8352,21 +8070,20 @@ Check if the provided argument is not `null` and that its `Symbol.iterator` prop ```js const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function'; -``` +```
    -Examples - -```js + Examples + + ```js isArrayLike(document.querySelectorAll('.className')); // true isArrayLike('abc'); // true isArrayLike(null); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isBoolean @@ -8376,20 +8093,19 @@ Use `typeof` to check if a value is classified as a boolean primitive. ```js const isBoolean = val => typeof val === 'boolean'; -``` +```
    -Examples - -```js + Examples + + ```js isBoolean(null); // false isBoolean(false); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isEmpty @@ -8399,12 +8115,12 @@ Check if the provided value is `null` or if its `length` is equal to `0`. ```js const isEmpty = val => val == null || !(Object.keys(val) || val).length; -``` +```
    -Examples - -```js + Examples + + ```js isEmpty(new Map()); // true isEmpty(new Set()); // true isEmpty([]); // true @@ -8418,9 +8134,8 @@ isEmpty(true); // true - type is not considered a collection ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isFunction @@ -8430,20 +8145,19 @@ Use `typeof` to check if a value is classified as a function primitive. ```js const isFunction = val => typeof val === 'function'; -``` +```
    -Examples - -```js + Examples + + ```js isFunction('x'); // false isFunction(x => x); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isNil @@ -8453,20 +8167,19 @@ Use the strict equality operator to check if the value and of `val` are equal to ```js const isNil = val => val === undefined || val === null; -``` +```
    -Examples - -```js + Examples + + ```js isNil(null); // true isNil(undefined); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isNull @@ -8476,19 +8189,18 @@ Use the strict equality operator to check if the value and of `val` are equal to ```js const isNull = val => val === null; -``` +```
    -Examples - -```js + Examples + + ```js isNull(null); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isNumber @@ -8498,20 +8210,19 @@ Use `typeof` to check if a value is classified as a number primitive. ```js const isNumber = val => typeof val === 'number'; -``` +```
    -Examples - -```js + Examples + + ```js isNumber('1'); // false isNumber(1); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isObject @@ -8522,12 +8233,12 @@ If the value is `null` or `undefined`, create and return an empty object. Οther ```js const isObject = obj => obj === Object(obj); -``` +```
    -Examples - -```js + Examples + + ```js isObject([1, 2, 3, 4]); // true isObject([]); // true isObject(['Hello!']); // true @@ -8537,9 +8248,8 @@ isObject(true); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isObjectLike @@ -8549,12 +8259,12 @@ Check if the provided value is not `null` and its `typeof` is equal to `'object' ```js const isObjectLike = val => val !== null && typeof val === 'object'; -``` +```
    -Examples - -```js + Examples + + ```js isObjectLike({}); // true isObjectLike([1, 2, 3]); // true isObjectLike(x => x); // false @@ -8562,9 +8272,8 @@ isObjectLike(null); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isPlainObject @@ -8574,20 +8283,19 @@ Check if the provided value is truthy, use `typeof` to check if it is an object ```js const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object; -``` +```
    -Examples - -```js + Examples + + ```js isPlainObject({ a: 1 }); // true isPlainObject(new Map()); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isPrimitive @@ -8599,12 +8307,12 @@ Since `typeof null` evaluates to `'object'`, it needs to be directly compared. ```js const isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null; -``` +```
    -Examples - -```js + Examples + + ```js isPrimitive(null); // true isPrimitive(50); // true isPrimitive('Hello!'); // true @@ -8614,9 +8322,8 @@ isPrimitive([]); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isPromiseLike @@ -8629,12 +8336,12 @@ const isPromiseLike = obj => obj !== null && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; -``` +```
    -Examples - -```js + Examples + + ```js isPromiseLike({ then: function() { return ''; @@ -8645,9 +8352,8 @@ isPromiseLike({}); // false ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isString @@ -8657,19 +8363,18 @@ Use `typeof` to check if a value is classified as a string primitive. ```js const isString = val => typeof val === 'string'; -``` +```
    -Examples - -```js + Examples + + ```js isString('10'); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isSymbol @@ -8679,19 +8384,18 @@ Use `typeof` to check if a value is classified as a symbol primitive. ```js const isSymbol = val => typeof val === 'symbol'; -``` +```
    -Examples - -```js + Examples + + ```js isSymbol(Symbol('x')); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isUndefined @@ -8701,19 +8405,18 @@ Use the strict equality operator to check if the value and of `val` are equal to ```js const isUndefined = val => val === undefined; -``` +```
    -Examples - -```js + Examples + + ```js isUndefined(undefined); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isValidJSON @@ -8730,25 +8433,24 @@ const isValidJSON = obj => { return false; } }; -``` +```
    -Examples - -```js + Examples + + ```js isValidJSON('{"name":"Adam","age":20}'); // true isValidJSON('{"name":"Adam",age:"20"}'); // false isValidJSON(null); // true ```
    + +[⬆ Back to top](#table-of-contents) -
    [⬆ Back to top](#table-of-contents) - ---- - ## πŸ”§ Utility - -### castArray + +--- +## πŸ”§ Utility### castArray Casts the provided value as an array if it's not one. @@ -8756,20 +8458,19 @@ Use `Array.isArray()` to determine if `val` is an array and return it as-is or e ```js const castArray = val => (Array.isArray(val) ? val : [val]); -``` +```
    -Examples - -```js + Examples + + ```js castArray('foo'); // ['foo'] castArray([1]); // [1] ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### cloneRegExp @@ -8779,20 +8480,19 @@ Use `new RegExp()`, `RegExp.source` and `RegExp.flags` to clone the given regula ```js const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags); -``` +```
    -Examples - -```js + Examples + + ```js const regExp = /lorem ipsum/gi; const regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### coalesce @@ -8802,19 +8502,18 @@ Use `Array.find()` to return the first non `null`/`undefined` argument. ```js const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); -``` +```
    -Examples - -```js + Examples + + ```js coalesce(null, undefined, '', NaN, 'Waldo'); // "" ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### coalesceFactory @@ -8824,20 +8523,19 @@ Use `Array.find()` to return the first argument that returns `true` from the pro ```js const coalesceFactory = valid => (...args) => args.find(valid); -``` +```
    -Examples - -```js + Examples + + ```js const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_)); customCoalesce(undefined, null, NaN, '', 'Waldo'); // "Waldo" ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### extendHex @@ -8854,20 +8552,19 @@ const extendHex = shortHex => .split('') .map(x => x + x) .join(''); -``` +```
    -Examples - -```js + Examples + + ```js extendHex('#03f'); // '#0033ff' extendHex('05a'); // '#0055aa' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### getURLParameters @@ -8882,20 +8579,19 @@ const getURLParameters = url => (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), {} ); -``` +```
    -Examples - -```js + Examples + + ```js getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'} getURLParameters('google.com'); // {} ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### hexToRGB ![advanced](/advanced.svg) @@ -8923,21 +8619,20 @@ const hexToRGB = hex => { ')' ); }; -``` +```
    -Examples - -```js + 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) - + +[⬆ Back to top](#table-of-contents) ### httpGet @@ -8956,12 +8651,12 @@ const httpGet = (url, callback, err = console.error) => { request.onerror = () => err(request); request.send(); }; -``` +```
    -Examples - -```js + Examples + + ```js httpGet( 'https://jsonplaceholder.typicode.com/posts/1', console.log @@ -8976,9 +8671,8 @@ Logs: { ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### httpPost @@ -9000,12 +8694,12 @@ const httpPost = (url, data, callback, err = console.error) => { request.onerror = () => err(request); request.send(data); }; -``` +```
    -Examples - -```js + Examples + + ```js const newPost = { userId: 1, id: 1337, @@ -9037,9 +8731,8 @@ Logs: { ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### isBrowser @@ -9051,20 +8744,19 @@ If both of them are not `undefined`, then the current environment is assumed to ```js const isBrowser = () => ![typeof window, typeof document].includes('undefined'); -``` +```
    -Examples - -```js + Examples + + ```js isBrowser(); // true (browser) isBrowser(); // false (Node) ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### mostPerformant @@ -9083,12 +8775,12 @@ const mostPerformant = (fns, iterations = 10000) => { }); return times.indexOf(Math.min(...times)); }; -``` +```
    -Examples - -```js + Examples + + ```js mostPerformant([ () => { // Loops through the entire array before returning `false` @@ -9102,9 +8794,8 @@ mostPerformant([ ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### nthArg @@ -9114,12 +8805,12 @@ Use `Array.slice()` to get the desired argument at index `n`. ```js const nthArg = n => (...args) => args.slice(n)[0]; -``` +```
    -Examples - -```js + Examples + + ```js const third = nthArg(2); third(1, 2, 3); // 3 third(1, 2); // undefined @@ -9128,9 +8819,8 @@ last(1, 2, 3, 4, 5); // 5 ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### parseCookie @@ -9149,19 +8839,18 @@ const parseCookie = str => acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim()); return acc; }, {}); -``` +```
    -Examples - -```js + Examples + + ```js parseCookie('foo=bar; equation=E%3Dmc%5E2'); // { foo: 'bar', equation: 'E=mc^2' } ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### prettyBytes ![advanced](/advanced.svg) @@ -9181,21 +8870,20 @@ const prettyBytes = (num, precision = 3, addSpace = true) => { const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision)); return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent]; }; -``` +```
    -Examples - -```js + Examples + + ```js prettyBytes(1000); // "1 KB" prettyBytes(-27145424323.5821, 5); // "-27.145 GB" prettyBytes(123456789, 3, false); // "123MB" ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### randomHexColorCode @@ -9208,19 +8896,18 @@ const randomHexColorCode = () => { let n = (Math.random() * 0xfffff * 1000000).toString(16); return '#' + n.slice(0, 6); }; -``` +```
    -Examples - -```js + Examples + + ```js randomHexColorCode(); // "#e34155" ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### RGBToHex @@ -9230,19 +8917,18 @@ Convert given RGB parameters to hexadecimal string using bitwise left-shift oper ```js const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); -``` +```
    -Examples - -```js + Examples + + ```js RGBToHex(255, 165, 1); // 'ffa501' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### serializeCookie @@ -9252,19 +8938,18 @@ Use template literals and `encodeURIComponent()` to create the appropriate strin ```js const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; -``` +```
    -Examples - -```js + Examples + + ```js serializeCookie('foo', 'bar'); // 'foo=bar' ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### timeTaken @@ -9279,19 +8964,18 @@ const timeTaken = callback => { console.timeEnd('timeTaken'); return r; }; -``` +```
    -Examples - -```js + Examples + + ```js timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### toCurrency @@ -9302,12 +8986,12 @@ Use `Intl.NumberFormat` to enable country / currency sensitive formatting. ```js const toCurrency = (n, curr, LanguageFormat = undefined) => Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n); -``` +```
    -Examples - -```js + Examples + + ```js toCurrency(123456.789, 'EUR'); // €123,456.79 | currency: Euro | currencyLangFormat: Local toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79 | currency: US Dollar | currencyLangFormat: English (United States) toCurrency(123456.789, 'USD', 'fa'); // Ϋ±Ϋ²Ϋ³Ω¬Ϋ΄Ϋ΅ΫΆΩ«Ϋ·ΫΉ ؜$ | currency: US Dollar | currencyLangFormat: Farsi @@ -9316,9 +9000,8 @@ toCurrency(322342436423.2435, 'JPY', 'fi'); // 322 342 436 423 Β₯ | currency: Ja ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### toDecimalMark @@ -9326,19 +9009,18 @@ Use `toLocaleString()` to convert a float-point arithmetic to the [Decimal mark] ```js const toDecimalMark = num => num.toLocaleString('en-US'); -``` +```
    -Examples - -```js + Examples + + ```js toDecimalMark(12305030388.9087); // "12,305,030,388.909" ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### toOrdinalSuffix @@ -9359,19 +9041,18 @@ const toOrdinalSuffix = num => { ? int + ordinals[digits[0] - 1] : int + ordinals[3]; }; -``` +```
    -Examples - -```js + Examples + + ```js toOrdinalSuffix('123'); // "123rd" ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### validateNumber @@ -9383,19 +9064,18 @@ Use `Number()` to check if the coercion holds. ```js const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; -``` +```
    -Examples - -```js + Examples + + ```js validateNumber('10'); // true ```
    - -
    [⬆ Back to top](#table-of-contents) - + +[⬆ Back to top](#table-of-contents) ### yesNo @@ -9407,12 +9087,12 @@ Omit the second argument, `def` to set the default answer as `no`. ```js const yesNo = (val, def = false) => /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def; -``` +```
    -Examples - -```js + Examples + + ```js yesNo('Y'); // true yesNo('yes'); // true yesNo('No'); // false @@ -9420,8 +9100,8 @@ yesNo('Foo', true); // true ```
    - -
    [⬆ Back to top](#table-of-contents) + +[⬆ Back to top](#table-of-contents) ## Collaborators diff --git a/package-lock.json b/package-lock.json index cde2cebe0..a1a8dbdde 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5696,9 +5696,9 @@ } }, "markdown-builder": { - "version": "0.8.1", - "resolved": "https://registry.npmjs.org/markdown-builder/-/markdown-builder-0.8.1.tgz", - "integrity": "sha512-zqOAYg8jqUM6gB4WkcJ/K5HkqPUL33VAqNrebHSxlkXcEcjDTeKMNqUC8/bND4tKRu72lRFrTmmGYRtlevvXZQ==", + "version": "0.8.3-dev", + "resolved": "https://registry.npmjs.org/markdown-builder/-/markdown-builder-0.8.3-dev.tgz", + "integrity": "sha512-NJp9MW/odYYP8z1lEEwDW3k+iVnzW1xaJqwWbjlzsAAA1kZohi6Cf3bQkWKZsxPJTZACgYd/aKpmunLSD1u2Bw==", "requires": { "husky": "1.0.0-rc.14" } diff --git a/package.json b/package.json index 2952c6c1f..92d5c0451 100644 --- a/package.json +++ b/package.json @@ -52,7 +52,7 @@ }, "homepage": "https://github.com/Chalarangelo/30-seconds-of-code#readme", "dependencies": { - "markdown-builder": "^0.8.1" + "markdown-builder": "^0.8.3-dev" }, "jest": { "reporters": [ diff --git a/snippets_archive/README.md b/snippets_archive/README.md index abc633d5c..51ace3c7e 100644 --- a/snippets_archive/README.md +++ b/snippets_archive/README.md @@ -1,4 +1,4 @@ -![Logo](/logo.png "") +![Logo](/logo.png) # Snippets Archive These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are. ## Table of Contents @@ -38,13 +38,12 @@ const JSONToDate = arr => {
    Examples -```js + ```js JSONToDate(/Date(1489525200000)/); // "14/3/2017" ```
    - [⬆ Back to top](#table-of-contents) ### speechSynthesis @@ -67,13 +66,12 @@ const speechSynthesis = message => {
    Examples -```js + ```js speechSynthesis('Hello, World'); // // plays the message ```
    - [⬆ Back to top](#table-of-contents) ### binarySearch @@ -99,14 +97,13 @@ const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
    Examples -```js + ```js binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2 binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1 ```
    - [⬆ Back to top](#table-of-contents) ### cleanObj @@ -132,14 +129,13 @@ const cleanObj = (obj, keysToKeep = [], childIndicator) => {
    Examples -```js + ```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) ### collatz @@ -155,13 +151,12 @@ const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);
    Examples -```js + ```js collatz(8); // 4 ```
    - [⬆ Back to top](#table-of-contents) ### countVowels @@ -177,14 +172,13 @@ const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
    Examples -```js + ```js countVowels('foobar'); // 3 countVowels('gym'); // 0 ```
    - [⬆ Back to top](#table-of-contents) ### factors @@ -226,7 +220,7 @@ const factors = (num, primes = false) => {
    Examples -```js + ```js factors(12); // [2,3,4,6,12] factors(12, true); // [2,3] factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12] @@ -235,7 +229,6 @@ factors(-12, true); // [2,3]
    - [⬆ Back to top](#table-of-contents) ### fibonacciCountUntilNum @@ -252,13 +245,12 @@ const fibonacciCountUntilNum = num =>
    Examples -```js + ```js fibonacciCountUntilNum(10); // 7 ```
    - [⬆ Back to top](#table-of-contents) ### fibonacciUntilNum @@ -282,13 +274,12 @@ const fibonacciUntilNum = num => {
    Examples -```js + ```js fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ] ```
    - [⬆ Back to top](#table-of-contents) ### httpDelete @@ -313,7 +304,7 @@ const httpDelete = (url, callback, err = console.error) => {
    Examples -```js + ```js httpDelete('https://website.com/users/123', request => { console.log(request.responseText); }); // 'Deletes a user from the database' @@ -321,7 +312,6 @@ httpDelete('https://website.com/users/123', request => {
    - [⬆ Back to top](#table-of-contents) ### httpPut @@ -348,7 +338,7 @@ const httpPut = (url, data, callback, err = console.error) => {
    Examples -```js + ```js const password = "fooBaz"; const data = JSON.stringify(password); httpPut('https://website.com/users/123', data, request => { @@ -358,7 +348,6 @@ httpPut('https://website.com/users/123', data, request => {
    - [⬆ Back to top](#table-of-contents) ### isArmstrongNumber @@ -377,14 +366,13 @@ const isArmstrongNumber = digits =>
    Examples -```js + ```js isArmstrongNumber(1634); // true isArmstrongNumber(56); // false ```
    - [⬆ Back to top](#table-of-contents) ### isSimilar @@ -404,14 +392,13 @@ const isSimilar = (pattern, str) =>
    Examples -```js + ```js isSimilar('rt','Rohit'); // true isSimilar('tr','Rohit'); // false ```
    - [⬆ Back to top](#table-of-contents) ### levenshteinDistance @@ -444,7 +431,7 @@ const levenshteinDistance = (string1, string2) => {
    Examples -```js + ```js levenshteinDistance('30-seconds-of-code','30-seconds-of-python-code'); // 7 const compareStrings = (string1,string2) => (100 - levenshteinDistance(string1,string2) / Math.max(string1.length,string2.length)); compareStrings('30-seconds-of-code', '30-seconds-of-python-code'); // 99.72 (%) @@ -452,7 +439,6 @@ compareStrings('30-seconds-of-code', '30-seconds-of-python-code'); // 99.72 (%)
    - [⬆ Back to top](#table-of-contents) ### quickSort @@ -477,14 +463,13 @@ const quickSort = ([n, ...nums], desc) =>
    Examples -```js + ```js quickSort([4, 1, 3, 2]); // [1,2,3,4] quickSort([4, 1, 3, 2], true); // [4,3,2,1] ```
    - [⬆ Back to top](#table-of-contents) ### removeVowels @@ -501,14 +486,13 @@ const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl);
    Examples -```js + ```js removeVowels("foobAr"); // "fbr" removeVowels("foobAr","*"); // "f**b*r" ```
    - [⬆ Back to top](#table-of-contents) ### solveRPN @@ -555,14 +539,13 @@ const solveRPN = rpn => {
    Examples -```js + ```js solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5 solveRPN('2 3 ^'); // 8 ```
    - [⬆ Back to top](#table-of-contents) ### howManyTimes @@ -591,7 +574,7 @@ const howManyTimes = (num, divisor) => {
    Examples -```js + ```js howManyTimes(100, 2); // 2 howManyTimes(100, 2.5); // 2 howManyTimes(100, 0); // 0 @@ -600,6 +583,5 @@ howManyTimes(100, -1); // Infinity
    - [⬆ Back to top](#table-of-contents)