From b1af834f2751eea3aef05f65325fed975d159dfb Mon Sep 17 00:00:00 2001 From: King Date: Wed, 7 Feb 2018 11:05:46 -0500 Subject: [PATCH 01/35] update mapObject basic test --- test/mapObject/mapObject.test.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/mapObject/mapObject.test.js b/test/mapObject/mapObject.test.js index 044c43b19..294bdcd00 100644 --- a/test/mapObject/mapObject.test.js +++ b/test/mapObject/mapObject.test.js @@ -5,11 +5,12 @@ test('Testing mapObject', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof mapObject === 'function', 'mapObject is a Function'); - const squareIt = arr => mapObject(arr, a => a * a); - t.deepEqual(squareIt([1, 2, 3]), { 1: 1, 2: 4, 3: 9 }, "Maps the values of an array to an object using a function"); - //t.deepEqual(mapObject(args..), 'Expected'); + t.deepEqual(mapObject([1, 2, 3], a => a * a), { 1: 1, 2: 4, 3: 9 }, "mapObject([1, 2, 3], a => a * a) returns { 1: 1, 2: 4, 3: 9 }"); + t.deepEqual(mapObject([1, 2, 3, 4], (a, b) => b - a), { 1: -1, 2: -1, 3: -1, 4: -1 }, 'mapObject([1, 2, 3, 4], (a, b) => b - a) returns { 1: -1, 2: -1, 3: -1, 4: -1 }'); + t.deepEqual(mapObject([1, 2, 3, 4], (a, b) => a - b), { 1: 1, 2: 1, 3: 1, 4: 1 }, 'mapObject([1, 2, 3, 4], (a, b) => a - b) returns { 1: 1, 2: 1, 3: 1, 4: 1 }'); + //t.equal(mapObject(args..), 'Expected'); //t.false(mapObject(args..), 'Expected'); //t.throws(mapObject(args..), 'Expected'); t.end(); -}); \ No newline at end of file +}); From 6e277ec593f38087e4f55fbbdc4e065fdfbf44ff Mon Sep 17 00:00:00 2001 From: atomiks Date: Thu, 8 Feb 2018 14:08:36 +1000 Subject: [PATCH 02/35] Shorten runAsync.md --- snippets/runAsync.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/snippets/runAsync.md b/snippets/runAsync.md index f52f400e9..09c116fbf 100644 --- a/snippets/runAsync.md +++ b/snippets/runAsync.md @@ -8,9 +8,8 @@ Return a promise, listening for `onmessage` and `onerror` events and resolving t ```js const runAsync = fn => { - const blob = `var fn = ${fn.toString()}; postMessage(fn());`; const worker = new Worker( - URL.createObjectURL(new Blob([blob]), { + URL.createObjectURL(new Blob([`postMessage((${fn})());`]), { type: 'application/javascript; charset=utf-8' }) ); From 957f72f297243499a9ae053996d64909b26f3e7d Mon Sep 17 00:00:00 2001 From: Dave Henton Date: Thu, 8 Feb 2018 08:29:30 -0800 Subject: [PATCH 03/35] Create .codeclimate.yml --- .codeclimate.yml | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 .codeclimate.yml diff --git a/.codeclimate.yml b/.codeclimate.yml new file mode 100644 index 000000000..8c3e549cd --- /dev/null +++ b/.codeclimate.yml @@ -0,0 +1,32 @@ +version: "2" # required to adjust maintainability checks +checks: + argument-count: + config: + threshold: 4 + complex-logic: + config: + threshold: 4 + file-lines: + config: + threshold: 250 + method-complexity: + config: + threshold: 5 + method-count: + config: + threshold: 20 + method-lines: + config: + threshold: 25 + nested-control-flow: + config: + threshold: 4 + return-statements: + config: + threshold: 4 + similar-code: + config: + threshold: # language-specific defaults. an override will affect all languages. + identical-code: + config: + threshold: # language-specific defaults. an override will affect all languages From c850efa15893a5a46d1fd520e42eeb199a8be818 Mon Sep 17 00:00:00 2001 From: Dave Henton Date: Thu, 8 Feb 2018 08:42:05 -0800 Subject: [PATCH 04/35] Update .codeclimate.yml --- .codeclimate.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.codeclimate.yml b/.codeclimate.yml index 8c3e549cd..0652ca2f6 100644 --- a/.codeclimate.yml +++ b/.codeclimate.yml @@ -2,7 +2,7 @@ version: "2" # required to adjust maintainability checks checks: argument-count: config: - threshold: 4 + threshold: 2 complex-logic: config: threshold: 4 From 937930bd09752fff92a14ba2c2b5a7d46f67e578 Mon Sep 17 00:00:00 2001 From: Dave Henton Date: Thu, 8 Feb 2018 08:44:30 -0800 Subject: [PATCH 05/35] Update .codeclimate.yml --- .codeclimate.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.codeclimate.yml b/.codeclimate.yml index 0652ca2f6..8c3e549cd 100644 --- a/.codeclimate.yml +++ b/.codeclimate.yml @@ -2,7 +2,7 @@ version: "2" # required to adjust maintainability checks checks: argument-count: config: - threshold: 2 + threshold: 4 complex-logic: config: threshold: 4 From 070566712688de103cc1cb6fe326224bc9362881 Mon Sep 17 00:00:00 2001 From: Dave Henton Date: Thu, 8 Feb 2018 09:08:59 -0800 Subject: [PATCH 06/35] Update .codeclimate.yml This adds ESLint and markdownlint to your analysis. Be sure to check out the docs for each of these plugins if you'd like to tweak their configuration further. - https://docs.codeclimate.com/docs/markdownlint https://docs.codeclimate.com/docs/eslint --- .codeclimate.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.codeclimate.yml b/.codeclimate.yml index 8c3e549cd..a2f87478e 100644 --- a/.codeclimate.yml +++ b/.codeclimate.yml @@ -1,4 +1,9 @@ version: "2" # required to adjust maintainability checks +plugins: + eslint: + enabled: true + markdownlint: + enabled: true checks: argument-count: config: From 8f8eb5da6197e31eb2dfe400cb5264035c2b0cd7 Mon Sep 17 00:00:00 2001 From: 30secondsofcode <30secondsofcode@gmail.com> Date: Thu, 8 Feb 2018 20:21:06 +0000 Subject: [PATCH 07/35] Travis build: 1609 [cron] --- test/testlog | 3436 +++++++++++++++++++++++++------------------------- 1 file changed, 1720 insertions(+), 1716 deletions(-) diff --git a/test/testlog b/test/testlog index ad8982482..e9bb2e570 100644 --- a/test/testlog +++ b/test/testlog @@ -1,1765 +1,1769 @@ -Test log for: Thu Feb 08 2018 16:12:32 GMT+0200 (GTB Standard Time) +Test log for: Thu Feb 08 2018 20:21:00 GMT+0000 (UTC) -> 30-seconds-of-code@0.0.1 test G:\My Files\git Repositories\30-seconds-of-code +> 30-seconds-of-code@0.0.1 test /home/travis/build/Chalarangelo/30-seconds-of-code > tape test/**/*.test.js | tap-spec - Testing anagrams - - √ anagrams is a Function - √ Generates all anagrams of a string - √ Works for single-letter strings - √ Works for empty strings - - Testing arrayToHtmlList - - √ arrayToHtmlList is a Function - - Testing ary - - √ ary is a Function - √ Discards arguments with index >=n - - Testing atob - - √ atob is a Function - √ atob("Zm9vYmFy") equals "foobar" - √ atob("Z") returns "" - - Testing attempt - - √ attempt is a Function - √ Returns a value - √ Returns an error - - Testing average - - √ average is a Function - √ average(true) returns 0 - √ average(false) returns 1 - √ average(9, 1) returns 5 - √ average(153, 44, 55, 64, 71, 1122, 322774, 2232, 23423, 234, 3631) returns 32163.909090909092 - √ average(1, 2, 3) returns 2 - √ average(null) returns 0 - √ average(1, 2, 3) returns NaN - √ average(String) returns NaN - √ average({ a: 123}) returns NaN - √ average([undefined, 0, string]) returns NaN - √ head([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]) takes less than 2s to run - - Testing averageBy - - √ averageBy is a Function - √ Produces the right result with a function - √ Produces the right result with a property name - - Testing binarySearch - - √ binarySearch is a Function - √ Finds item in array - √ Returns -1 when not found - √ Works with empty arrays - √ Works for one element arrays - - Testing bind - - √ bind is a Function - √ Binds to an object context - - Testing bindAll - - √ bindAll is a Function - √ Binds to an object context - - Testing bindKey - - √ bindKey is a Function - √ Binds function to an object context - - Testing bottomVisible - - √ bottomVisible is a Function - - Testing btoa - - √ btoa is a Function - √ btoa("foobar") equals "Zm9vYmFy" - - Testing byteSize - - √ byteSize is a Function - √ Works for a single letter - √ Works for a common string - √ Works for emoji - - Testing call - - √ call is a Function - √ Calls function on given object - - Testing capitalize - - √ capitalize is a Function - √ Capitalizes the first letter of a string - √ Capitalizes the first letter of a string - √ Works with characters - √ Works with single character words - - Testing capitalizeEveryWord - - √ capitalizeEveryWord is a Function - √ Capitalizes the first letter of every word in a string - √ Works with characters - √ Works with one word string - - Testing castArray - - √ castArray is a Function - √ Works for single values - √ Works for arrays with one value - √ Works for arrays with multiple value - √ Works for strings - √ Works for objects - - Testing chainAsync - - √ chainAsync is a Function - - Testing chunk - - √ chunk is a Function - √ chunk([1, 2, 3, 4, 5], 2) returns [[1,2],[3,4],[5]] - √ chunk([]) returns [] - √ chunk(123) returns [] - √ chunk({ a: 123}) returns [] - √ chunk(string, 2) returns [ st, ri, ng ] - √ chunk() throws an error - √ chunk(undefined) throws an error - √ chunk(null) throws an error - √ chunk(This is a string, 2) takes less than 2s to run - - Testing clampNumber - - √ clampNumber is a Function - √ Clamps num within the inclusive range specified by the boundary values a and b - - Testing cleanObj - - √ cleanObj is a Function - √ Removes any properties except the ones specified from a JSON object - - Testing cloneRegExp - - √ cloneRegExp is a Function - √ Clones regular expressions properly - - Testing coalesce - - √ coalesce is a Function - √ Returns the first non-null/undefined argument - - Testing coalesceFactory - - √ coalesceFactory is a Function - √ Returns a customized coalesce function - - Testing collatz - - √ collatz is a Function - √ When n is even, divide by 2 - √ When n is odd, times by 3 and add 1 - √ Eventually reaches 1 - - Testing collectInto - - √ collectInto is a Function - - Testing colorize - - √ colorize is a Function - - Testing compact - - √ compact is a Function - √ Removes falsey values from an array - - Testing compose - - √ compose is a Function - √ Performs right-to-left function composition - - Testing composeRight - - √ composeRight is a Function - √ Performs left-to-right function composition - - Testing converge - - √ converge is a Function - √ Produces the average of the array - √ Produces the strange concatenation - - Testing copyToClipboard - - √ copyToClipboard is a Function - - Testing countBy - - √ countBy is a Function - √ Works for functions - √ Works for property names - - Testing countOccurrences - - √ countOccurrences is a Function - √ Counts the occurrences of a value in an array - - Testing countVowels - - √ countVowels is a Function - - Testing createElement - - √ createElement is a Function - - Testing createEventHub - - √ createEventHub is a Function - - Testing currentURL - - √ currentURL is a Function - - Testing curry - - √ curry is a Function - √ curries a Math.pow - √ curries a Math.min - - Testing debounce - - √ debounce is a Function - - Testing decapitalize - - √ decapitalize is a Function - √ Works with default parameter - √ Works with second parameter set to true - - Testing deepClone - - √ deepClone is a Function - √ Shallow cloning works - √ Deep cloning works - - Testing deepFlatten - - √ deepFlatten is a Function - √ Deep flattens an array - - Testing defaults - - √ defaults is a Function - - Testing defer - - √ defer is a Function - - Testing delay - - √ delay is a Function - - Testing detectDeviceType - - √ detectDeviceType is a Function - - Testing difference - - √ difference is a Function - √ Returns the difference between two arrays - - Testing differenceBy - - √ differenceBy is a Function - √ Works using a native function and numbers - √ Works with arrow function and objects - - Testing differenceWith - - √ differenceWith is a Function - √ Filters out all values from an array - - Testing digitize - - √ digitize is a Function - √ Converts a number to an array of digits - - Testing distance - - √ distance is a Function - √ Calculates the distance between two points - - Testing drop - - √ drop is a Function - √ Works without the last argument - √ Removes appropriate element count as specified - √ Empties array given a count greater than length - - Testing dropRight - - √ dropRight is a Function - √ Returns a new array with n elements removed from the right - √ Returns a new array with n elements removed from the right - √ Returns a new array with n elements removed from the right - - Testing dropRightWhile - - √ dropRightWhile is a Function - √ Removes elements from the end of an array until the passed function returns true. - - Testing dropWhile - - √ dropWhile is a Function - √ Removes elements in an array until the passed function returns true. - - Testing elementIsVisibleInViewport - - √ elementIsVisibleInViewport is a Function - - Testing elo - - √ elo is a Function - √ Standard 1v1s - √ should be equivalent - √ 4 player FFA, all same rank - - Testing equals - - √ equals is a Function - √ { a: [2, {e: 3}], b: [4], c: 'foo' } is equal to { a: [2, {e: 3}], b: [4], c: 'foo' } - √ [1,2,3] is equal to [1,2,3] - √ { a: [2, 3], b: [4] } is not equal to { a: [2, 3], b: [6] } - √ [1,2,3] is not equal to [1,2,4] - √ [1, 2, 3] should be equal to { 0: 1, 1: 2, 2: 3 }) - type is different, but their enumerable properties match. - - Testing escapeHTML - - √ escapeHTML is a Function - √ Escapes a string for use in HTML - - Testing escapeRegExp - - √ escapeRegExp is a Function - √ Escapes a string to use in a regular expression - - Testing everyNth - - √ everyNth is a Function - √ Returns every nth element in an array - - Testing extendHex - - √ extendHex is a Function - √ Extends a 3-digit color code to a 6-digit color code - √ Extends a 3-digit color code to a 6-digit color code - - Testing factorial - - √ factorial is a Function - √ Calculates the factorial of 720 - √ Calculates the factorial of 0 - √ Calculates the factorial of 1 - √ Calculates the factorial of 4 - √ Calculates the factorial of 10 - - Testing factors - - √ factors is a Function - - Testing fibonacci - - √ fibonacci is a Function - √ Generates an array, containing the Fibonacci sequence - - Testing fibonacciCountUntilNum - - √ fibonacciCountUntilNum is a Function - - Testing fibonacciUntilNum - - √ fibonacciUntilNum is a Function - - Testing filterNonUnique - - √ filterNonUnique is a Function - √ Filters out the non-unique values in an array - - Testing findKey - - √ findKey is a Function - √ Returns the appropriate key - - Testing findLast - - √ findLast is a Function - √ Finds last element for which the given function returns true - - Testing findLastIndex - - √ findLastIndex is a Function - √ Finds last index for which the given function returns true - - Testing findLastKey - - √ findLastKey is a Function - √ Returns the appropriate key - - Testing flatten - - √ flatten is a Function - √ Flattens an array - √ Flattens an array - - Testing flattenObject - - √ flattenObject is a Function - √ Flattens an object with the paths for keys - √ Works with arrays - - Testing flip - - √ flip is a Function - √ Flips argument order - - Testing forEachRight - - √ forEachRight is a Function - √ Iterates over the array in reverse - - Testing formatDuration - - √ formatDuration is a Function - √ Returns the human readable format of the given number of milliseconds - √ Returns the human readable format of the given number of milliseconds - - Testing forOwn - - √ forOwn is a Function - √ Iterates over an element's key-value pairs - - Testing forOwnRight - - √ forOwnRight is a Function - √ Iterates over an element's key-value pairs in reverse - - Testing fromCamelCase - - √ fromCamelCase is a Function - √ Converts a string from camelcase - √ Converts a string from camelcase - √ Converts a string from camelcase - - Testing functionName - - √ functionName is a Function - √ Works for native functions - √ Works for functions - √ Works for arrow functions - - Testing functions - - √ functions is a Function - √ Returns own methods - √ Returns own and inherited methods - - Testing gcd - - √ gcd is a Function - √ Calculates the greatest common divisor between two or more numbers/arrays - √ Calculates the greatest common divisor between two or more numbers/arrays - - Testing geometricProgression - - √ geometricProgression is a Function - √ Initializes an array containing the numbers in the specified range - √ Initializes an array containing the numbers in the specified range - √ Initializes an array containing the numbers in the specified range - - Testing get - - √ get is a Function - √ Retrieve a property indicated by the selector from an object. - - Testing getColonTimeFromDate - - √ getColonTimeFromDate is a Function - - Testing getDaysDiffBetweenDates - - √ getDaysDiffBetweenDates is a Function - √ Returns the difference in days between two dates - - Testing getMeridiemSuffixOfInteger - - √ getMeridiemSuffixOfInteger is a Function - - Testing getScrollPosition - - √ getScrollPosition is a Function - - Testing getStyle - - √ getStyle is a Function - - Testing getType - - √ getType is a Function - √ Returns the native type of a value - - Testing getURLParameters - - √ getURLParameters is a Function - √ Returns an object containing the parameters of the current URL - - Testing groupBy - - √ groupBy is a Function - √ Groups the elements of an array based on the given function - √ Groups the elements of an array based on the given function - - Testing hammingDistance - - √ hammingDistance is a Function - √ retuns hamming disance between 2 values - - Testing hasClass - - √ hasClass is a Function - - Testing hasFlags - - √ hasFlags is a Function - - Testing hashBrowser - - √ hashBrowser is a Function - - Testing hashNode - - √ hashNode is a Function - - Testing head - - √ head is a Function - √ head({ a: 1234}) returns undefined - √ head([1, 2, 3]) returns 1 - √ head({ 0: false}) returns false - √ head(String) returns S - √ head(null) throws an Error - √ head(undefined) throws an Error - √ head() throws an Error - √ head([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]) takes less than 2s to run - - Testing hexToRGB - - √ hexToRGB is a Function - √ Converts a color code to a rgb() or rgba() string - √ Converts a color code to a rgb() or rgba() string - √ Converts a color code to a rgb() or rgba() string - - Testing hide - - √ hide is a Function - - Testing howManyTimes - - √ howManyTimes is a Function - - Testing httpDelete - - √ httpDelete is a Function - - Testing httpGet - - √ httpGet is a Function - - Testing httpPost - - √ httpPost is a Function - - Testing httpPut - - √ httpPut is a Function - - Testing httpsRedirect - - √ httpsRedirect is a Function - - Testing indexOfAll - - √ indexOfAll is a Function - √ Returns all indices of val in an array - √ Returns all indices of val in an array - - Testing initial - - √ initial is a Function - √ Returns all the elements of an array except the last one - - Testing initialize2DArray - - √ initialize2DArray is a Function - √ Initializes a 2D array of given width and height and value - - Testing initializeArrayWithRange - - √ initializeArrayWithRange is a Function - √ Initializes an array containing the numbers in the specified range - - Testing initializeArrayWithRangeRight - - √ initializeArrayWithRangeRight is a Function - - Testing initializeArrayWithValues - - √ initializeArrayWithValues is a Function - √ Initializes and fills an array with the specified values - - Testing inRange - - √ inRange is a Function - √ The given number falls within the given range - √ The given number falls within the given range - √ The given number does not falls within the given range - √ The given number does not falls within the given range - - Testing intersection - - √ intersection is a Function - √ Returns a list of elements that exist in both arrays - - Testing intersectionBy - - √ intersectionBy is a Function - √ Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both - - Testing intersectionWith - - √ intersectionWith is a Function - √ Returns a list of elements that exist in both arrays, using a provided comparator function - - Testing invertKeyValues - - √ invertKeyValues is a Function - √ invertKeyValues({ a: 1, b: 2, c: 1 }) returns { 1: [ 'a', 'c' ], 2: [ 'b' ] } - √ invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value) returns { group1: [ 'a', 'c' ], group2: [ 'b' ] } - - Testing is - - √ is is a Function - √ Works for arrays with data - √ Works for empty arrays - √ Works for arrays, not objects - √ Works for objects - √ Works for maps - √ Works for regular expressions - √ Works for sets - √ Works for weak maps - √ Works for weak sets - √ Works for strings - returns false for primitive - √ Works for strings - returns true when using constructor - √ Works for numbers - returns false for primitive - √ Works for numbers - returns true when using constructor - √ Works for booleans - returns false for primitive - √ Works for booleans - returns true when using constructor - √ Works for functions - - Testing isAbsoluteURL - - √ isAbsoluteURL is a Function - √ Given string is an absolute URL - √ Given string is an absolute URL - √ Given string is not an absolute URL - - Testing isArmstrongNumber - - √ isArmstrongNumber is a Function - - Testing isArray - - √ isArray is a Function - √ passed value is an array - √ passed value is not an array - - Testing isArrayBuffer - - √ isArrayBuffer is a Function - - Testing isArrayLike - - √ isArrayLike is a Function - √ Returns true for a string - √ Returns true for an array - √ Returns false for null - - Testing isBoolean - - √ isBoolean is a Function - √ passed value is not a boolean - √ passed value is not a boolean - - Testing isDivisible - - √ isDivisible is a Function - √ The number 6 is divisible by 3 - - Testing isEmpty - - √ isEmpty is a Function - √ Returns true for empty Map - √ Returns true for empty Set - √ Returns true for empty array - √ Returns true for empty object - √ Returns true for empty string - √ Returns false for non-empty array - √ Returns false for non-empty object - √ Returns false for non-empty string - √ Returns true - type is not considered a collection - √ Returns true - type is not considered a collection - - Testing isEven - - √ isEven is a Function - √ 4 is even number - √ undefined - - Testing isFunction - - √ isFunction is a Function - √ passed value is a function - √ passed value is not a function - - Testing isLowerCase - - √ isLowerCase is a Function - √ passed string is a lowercase - √ passed string is a lowercase - √ passed value is not a lowercase - - Testing isMap - - √ isMap is a Function - - Testing isNil - - √ isNil is a Function - √ Returns true for null - √ Returns true for undefined - √ Returns false for an empty string - - Testing isNull - - √ isNull is a Function - √ passed argument is a null - √ passed argument is a null - - Testing isNumber - - √ isNumber is a Function - √ passed argument is a number - √ passed argument is not a number - - Testing isObject - - √ isObject is a Function - √ isObject([1, 2, 3, 4]) is a object - √ isObject([]) is a object - √ isObject({ a:1 }) is a object - √ isObject(true) is not a object - - Testing isObjectLike - - √ isObjectLike is a Function - √ Returns true for an object - √ Returns true for an array - √ Returns false for a function - √ Returns false for null - - Testing isPlainObject - - √ isPlainObject is a Function - √ Returns true for a plain object - √ Returns false for a Map (example of non-plain object) - - Testing isPrime - - √ isPrime is a Function - √ passed number is a prime - - Testing isPrimitive - - √ isPrimitive is a Function - √ isPrimitive(null) is primitive - √ isPrimitive(undefined) is primitive - √ isPrimitive(string) is primitive - √ isPrimitive(true) is primitive - √ isPrimitive(50) is primitive - √ isPrimitive('Hello') is primitive - √ isPrimitive(false) is primitive - √ isPrimitive(Symbol()) is primitive - √ isPrimitive([1, 2, 3]) is not primitive - √ isPrimitive({ a: 123 }) is not primitive - √ isPrimitive({ a: 123 }) takes less than 2s to run - - Testing isPromiseLike - - √ isPromiseLike is a Function - √ Returns true for a promise-like object - √ Returns false for null - √ Returns false for an empty object - - Testing isRegExp - - √ isRegExp is a Function - - Testing isSet - - √ isSet is a Function - - Testing isSorted - - √ isSorted is a Function - √ Array is sorted in ascending order - √ Array is sorted in descending order - √ Array is not sorted, direction changed in array - - Testing isString - - √ isString is a Function - √ foo is a string - √ "10" is a string - √ Empty string is a string - √ 10 is not a string - √ true is not string - - Testing isSymbol - - √ isSymbol is a Function - √ Checks if the given argument is a symbol - - Testing isTravisCI - - √ isTravisCI is a Function - √ Not running on Travis, correctly evaluates - - Testing isTypedArray - - √ isTypedArray is a Function - - Testing isUndefined - - √ isUndefined is a Function - √ Returns true for undefined - - Testing isUpperCase - - √ isUpperCase is a Function - √ ABC is all upper case - √ abc is not all upper case - √ A3@$ is all uppercase - - Testing isValidJSON - - √ isValidJSON is a Function - √ {"name":"Adam","age":20} is a valid JSON - √ {"name":"Adam",age:"20"} is not a valid JSON - √ null is a valid JSON - - Testing isWeakMap - - √ isWeakMap is a Function - - Testing isWeakSet - - √ isWeakSet is a Function - - Testing join - - √ join is a Function - √ Joins all elements of an array into a string and returns this string - √ Joins all elements of an array into a string and returns this string - √ Joins all elements of an array into a string and returns this string - Testing JSONToDate - √ JSONToDate is a Function + ✔ JSONToDate is a Function Testing JSONToFile - √ JSONToFile is a Function - - Testing last - - √ last is a Function - √ last({ a: 1234}) returns undefined - √ last([1, 2, 3]) returns 3 - √ last({ 0: false}) returns undefined - √ last(String) returns g - √ last(null) throws an Error - √ last(undefined) throws an Error - √ last() throws an Error - √ last([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]) takes less than 2s to run - - Testing lcm - - √ lcm is a Function - √ Returns the least common multiple of two or more numbers. - √ Returns the least common multiple of two or more numbers. - - Testing longestItem - - √ longestItem is a Function - √ Returns the longest object - - Testing lowercaseKeys - - √ lowercaseKeys is a Function - √ Lowercases object keys - √ Does not mutate original object - - Testing luhnCheck - - √ luhnCheck is a Function - √ validates identification number - √ validates identification number - √ validates identification number - - Testing mapKeys - - √ mapKeys is a Function - √ Maps keys - - Testing mapObject - - √ mapObject is a Function - √ Maps the values of an array to an object using a function - - Testing mapValues - - √ mapValues is a Function - √ Maps values - - Testing mask - - √ mask is a Function - √ Replaces all but the last num of characters with the specified mask character - √ Replaces all but the last num of characters with the specified mask character - √ Replaces all but the last num of characters with the specified mask character - - Testing matches - - √ matches is a Function - √ Matches returns true for two similar objects - √ Matches returns false for two non-similar objects - - Testing matchesWith - - √ matchesWith is a Function - √ Returns true for two objects with similar values, based on the provided function - - Testing maxBy - - √ maxBy is a Function - √ Produces the right result with a function - √ Produces the right result with a property name - - Testing maxN - - √ maxN is a Function - √ Returns the n maximum elements from the provided array - √ Returns the n maximum elements from the provided array - - Testing median - - √ median is a Function - √ Returns the median of an array of numbers - √ Returns the median of an array of numbers - - Testing memoize - - √ memoize is a Function - √ Function works properly - √ Function works properly - √ Cache stores values - - Testing merge - - √ merge is a Function - √ Merges two objects - - Testing minBy - - √ minBy is a Function - √ Produces the right result with a function - √ Produces the right result with a property name - - Testing minN - - √ minN is a Function - √ Returns the n minimum elements from the provided array - √ Returns the n minimum elements from the provided array - - Testing negate - - √ negate is a Function - √ Negates a predicate function - - Testing nthArg - - √ nthArg is a Function - √ Returns the nth argument - √ Returns undefined if arguments too few - √ Works for negative values - - Testing nthElement - - √ nthElement is a Function - √ Returns the nth element of an array. - √ Returns the nth element of an array. - - Testing objectFromPairs - - √ objectFromPairs is a Function - √ Creates an object from the given key-value pairs. - - Testing objectToPairs - - √ objectToPairs is a Function - √ Creates an array of key-value pair arrays from an object. - - Testing observeMutations - - √ observeMutations is a Function - - Testing off - - √ off is a Function - - Testing omit - - √ omit is a Function - √ Omits the key-value pairs corresponding to the given keys from an object - - Testing omitBy - - √ omitBy is a Function - √ Creates an object composed of the properties the given function returns falsey for - - Testing on - - √ on is a Function - - Testing once - - √ once is a Function - - Testing onUserInputChange - - √ onUserInputChange is a Function - - Testing orderBy - - √ orderBy is a Function - √ Returns a sorted array of objects ordered by properties and orders. - √ Returns a sorted array of objects ordered by properties and orders. - - Testing over - - √ over is a Function - √ Applies given functions over multiple arguments - - Testing overArgs - - √ overArgs is a Function - √ Invokes the provided function with its arguments transformed - - Testing palindrome - - √ palindrome is a Function - √ Given string is a palindrome - √ Given string is not a palindrome - - Testing parseCookie - - √ parseCookie is a Function - √ Parses the cookie - - Testing partial - - √ partial is a Function - √ Prepends arguments - - Testing partialRight - - √ partialRight is a Function - √ Appends arguments - - Testing partition - - √ partition is a Function - √ Groups the elements into two arrays, depending on the provided function's truthiness for each element. - - Testing percentile - - √ percentile is a Function - √ Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value. - - Testing pick - - √ pick is a Function - √ Picks the key-value pairs corresponding to the given keys from an object. - - Testing pickBy - - √ pickBy is a Function - √ Creates an object composed of the properties the given function returns truthy for. - - Testing pipeAsyncFunctions - - √ pipeAsyncFunctions is a Function - √ Produces the appropriate hash - √ pipeAsyncFunctions result should be 15 - - Testing pipeFunctions - - √ pipeFunctions is a Function - √ Performs left-to-right function composition - - Testing pluralize - - √ pluralize is a Function - √ Produces the plural of the word - √ Produces the singular of the word - √ Produces the plural of the word - √ Prodices the defined plural of the word - √ Works with a dictionary - - Testing powerset - - √ powerset is a Function - √ Returns the powerset of a given array of numbers. - - Testing prettyBytes - - √ prettyBytes is a Function - √ Converts a number in bytes to a human-readable string. - √ Converts a number in bytes to a human-readable string. - √ Converts a number in bytes to a human-readable string. - - Testing primes - - √ primes is a Function - √ Generates primes up to a given number, using the Sieve of Eratosthenes. - - Testing promisify - - √ promisify is a Function - - Testing pull - - √ pull is a Function - √ Pulls the specified values - - Testing pullAtIndex - - √ pullAtIndex is a Function - √ Pulls the given values - √ Pulls the given values - - Testing pullAtValue - - √ pullAtValue is a Function - √ Pulls the specified values - √ Pulls the specified values - - Testing pullBy - - √ pullBy is a Function - √ Pulls the specified values - - Testing quickSort - - √ quickSort is a Function - √ quickSort([5, 6, 4, 3, 1, 2]) returns [1, 2, 3, 4, 5, 6] - √ quickSort([-1, 0, -2]) returns [-2, -1, 0] - √ quickSort() throws an error - √ quickSort(123) throws an error - √ quickSort({ 234: string}) throws an error - √ quickSort(null) throws an error - √ quickSort(undefined) throws an error - √ quickSort([11, 1, 324, 23232, -1, 53, 2, 524, 32, 13, 156, 133, 62, 12, 4]) takes less than 2s to run - - Testing randomHexColorCode - - √ randomHexColorCode is a Function - √ should be equal - - Testing randomIntArrayInRange - - √ randomIntArrayInRange is a Function - - Testing randomIntegerInRange - - √ randomIntegerInRange is a Function - - Testing randomNumberInRange - - √ randomNumberInRange is a Function - - Testing readFileLines - - √ readFileLines is a Function - - Testing rearg - - √ rearg is a Function - √ Reorders arguments in invoked function - - Testing redirect - - √ redirect is a Function - - Testing reducedFilter - - √ reducedFilter is a Function - √ Filter an array of objects based on a condition while also filtering out unspecified keys. - - Testing reduceSuccessive - - √ reduceSuccessive is a Function - √ Returns the array of successively reduced values - - Testing reduceWhich - - √ reduceWhich is a Function - √ Returns the minimum of an array - √ Returns the maximum of an array - √ Returns the object with the minimum specified value in an array - - Testing remove - - √ remove is a Function - √ Removes elements from an array for which the given function returns false - - Testing removeNonASCII - - √ removeNonASCII is a Function - √ Removes non-ASCII characters - - Testing removeVowels - - √ removeVowels is a Function - - Testing reverseString - - √ reverseString is a Function - √ Reverses a string. + ✔ JSONToFile is a Function Testing RGBToHex - √ RGBToHex is a Function - √ Converts the values of RGB components to a color code. - - Testing round - - √ round is a Function - √ round(1.005, 2) returns 1.01 - √ round(123.3423345345345345344, 11) returns 123.34233453453 - √ round(3.342, 11) returns 3.342 - √ round(1.005) returns 1 - √ round([1.005, 2]) returns NaN - √ round(string) returns NaN - √ round() returns NaN - √ round(132, 413, 4134) returns NaN - √ round({a: 132}, 413) returns NaN - √ round(123.3423345345345345344, 11) takes less than 2s to run - - Testing runAsync - - √ runAsync is a Function - - Testing runPromisesInSeries - - √ runPromisesInSeries is a Function - - Testing sample - - √ sample is a Function - - Testing sampleSize - - √ sampleSize is a Function - - Testing scrollToTop - - √ scrollToTop is a Function - - Testing sdbm - - √ sdbm is a Function - √ Hashes the input string into a whole number. - - Testing serializeCookie - - √ serializeCookie is a Function - √ Serializes the cookie - - Testing setStyle - - √ setStyle is a Function - - Testing shallowClone - - √ shallowClone is a Function - √ Shallow cloning works - √ Does not clone deeply - - Testing show - - √ show is a Function - - Testing shuffle - - √ shuffle is a Function - - Testing similarity - - √ similarity is a Function - √ Returns an array of elements that appear in both arrays. - - Testing size - - √ size is a Function - √ Get size of arrays, objects or strings. - √ Get size of arrays, objects or strings. - - Testing sleep - - √ sleep is a Function - - Testing solveRPN - - √ solveRPN is a Function - - Testing sortCharactersInString - - √ sortCharactersInString is a Function - √ Alphabetically sorts the characters in a string. - - Testing sortedIndex - - √ sortedIndex is a Function - √ Returns the lowest index at which value should be inserted into array in order to maintain its sort order. - √ Returns the lowest index at which value should be inserted into array in order to maintain its sort order. - - Testing sortedIndexBy - - √ sortedIndexBy is a Function - √ Returns the lowest index to insert the element without messing up the list order - - Testing sortedLastIndex - - √ sortedLastIndex is a Function - √ Returns the highest index to insert the element without messing up the list order - - Testing sortedLastIndexBy - - √ sortedLastIndexBy is a Function - √ Returns the highest index to insert the element without messing up the list order - - Testing speechSynthesis - - √ speechSynthesis is a Function - - Testing splitLines - - √ splitLines is a Function - √ Splits a multiline string into an array of lines. - - Testing spreadOver - - √ spreadOver is a Function - √ Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function. - - Testing standardDeviation - - √ standardDeviation is a Function - √ Returns the standard deviation of an array of numbers - √ Returns the standard deviation of an array of numbers - - Testing stripHTMLTags - - √ stripHTMLTags is a Function - √ Removes HTML tags - - Testing sum - - √ sum is a Function - √ Returns the sum of two or more numbers/arrays. - - Testing sumBy - - √ sumBy is a Function - - Testing sumPower - - √ sumPower is a Function - √ Returns the sum of the powers of all the numbers from start to end - √ Returns the sum of the powers of all the numbers from start to end - √ Returns the sum of the powers of all the numbers from start to end - - Testing symmetricDifference - - √ symmetricDifference is a Function - √ Returns the symmetric difference between two arrays. - - Testing symmetricDifferenceBy - - √ symmetricDifferenceBy is a Function - √ Returns the symmetric difference between two arrays, after applying the provided function to each array element of both - - Testing symmetricDifferenceWith - - √ symmetricDifferenceWith is a Function - √ Returns the symmetric difference between two arrays, using a provided function as a comparator - - Testing tail - - √ tail is a Function - √ Returns tail - √ Returns tail - - Testing take - - √ take is a Function - √ Returns an array with n elements removed from the beginning. - √ Returns an array with n elements removed from the beginning. - - Testing takeRight - - √ takeRight is a Function - √ Returns an array with n elements removed from the end - √ Returns an array with n elements removed from the end - - Testing takeRightWhile - - √ takeRightWhile is a Function - √ Removes elements until the function returns true - - Testing takeWhile - - √ takeWhile is a Function - √ Removes elements until the function returns true - - Testing throttle - - √ throttle is a Function - - Testing times - - √ times is a Function - √ Runs a function the specified amount of times - - Testing timeTaken - - √ timeTaken is a Function - - Testing toCamelCase - - √ toCamelCase is a Function - √ toCamelCase('some_database_field_name') returns someDatabaseFieldName - √ toCamelCase('Some label that needs to be camelized') returns someLabelThatNeedsToBeCamelized - √ toCamelCase('some-javascript-property') return someJavascriptProperty - √ toCamelCase('some-mixed_string with spaces_underscores-and-hyphens') returns someMixedStringWithSpacesUnderscoresAndHyphens - √ toCamelCase() throws a error - √ toCamelCase([]) throws a error - √ toCamelCase({}) throws a error - √ toCamelCase(123) throws a error - √ toCamelCase(some-mixed_string with spaces_underscores-and-hyphens) takes less than 2s to run - - Testing toCurrency - - √ toCurrency is a Function - √ currency: Euro | currencyLangFormat: Local - √ currency: US Dollar | currencyLangFormat: English (United States) - √ currency: Japanese Yen | currencyLangFormat: Local - - Testing toDecimalMark - - √ toDecimalMark is a Function - √ convert a float-point arithmetic to the Decimal mark form - - Testing toggleClass - - √ toggleClass is a Function - - Testing toKebabCase - - √ toKebabCase is a Function - √ toKebabCase('camelCase') returns camel-case - √ toKebabCase('some text') returns some-text - √ toKebabCase('some-mixed-string With spaces-underscores-and-hyphens') returns some-mixed-string-with-spaces-underscores-and-hyphens - √ toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') returns i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-some-xml-and-html - √ toKebabCase() return undefined - √ toKebabCase([]) throws an error - √ toKebabCase({}) throws an error - √ toKebabCase(123) throws an error - √ toKebabCase(IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML) takes less than 2s to run - - Testing tomorrow - - √ tomorrow is a Function - - Testing toOrdinalSuffix - - √ toOrdinalSuffix is a Function - √ Adds an ordinal suffix to a number - √ Adds an ordinal suffix to a number - √ Adds an ordinal suffix to a number - √ Adds an ordinal suffix to a number - - Testing toSafeInteger - - √ toSafeInteger is a Function - √ Number(toSafeInteger(3.2)) is a number - √ Converts a value to a safe integer - √ toSafeInteger('4.2') returns 4 - √ toSafeInteger(4.6) returns 5 - √ toSafeInteger([]) returns 0 - √ isNaN(toSafeInteger([1.5, 3124])) is true - √ isNaN(toSafeInteger('string')) is true - √ isNaN(toSafeInteger({})) is true - √ isNaN(toSafeInteger()) is true - √ toSafeInteger(Infinity) returns 9007199254740991 - √ toSafeInteger(3.2) takes less than 2s to run - - Testing toSnakeCase - - √ toSnakeCase is a Function - √ toSnakeCase('camelCase') returns camel_case - √ toSnakeCase('some text') returns some_text - √ toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens') returns some_mixed_string_with_spaces_underscores_and_hyphens - √ toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') returns i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html - √ toSnakeCase() returns undefined - √ toSnakeCase([]) throws an error - √ toSnakeCase({}) throws an error - √ toSnakeCase(123) throws an error - √ toSnakeCase(IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML) takes less than 2s to run - - Testing transform - - √ transform is a Function - √ Transforms an object - - Testing truncateString - - √ truncateString is a Function - √ Truncates a "boomerang" up to a specified length. - - Testing truthCheckCollection - - √ truthCheckCollection is a Function - √ second argument is truthy on all elements of a collection - - Testing unary - - √ unary is a Function - √ Discards arguments after the first one - - Testing unescapeHTML - - √ unescapeHTML is a Function - √ Unescapes escaped HTML characters. - - Testing unflattenObject - - √ unflattenObject is a Function - √ Unflattens an object with the paths for keys - - Testing unfold - - √ unfold is a Function - √ Works with a given function, producing an array - - Testing union - - √ union is a Function - √ union([1, 2, 3], [4, 3, 2]) returns [1, 2, 3, 4] - √ union('str', 'asd') returns [ 's', 't', 'r', 'a', 'd' ] - √ union([[], {}], [1, 2, 3]) returns [[], {}, 1, 2, 3] - √ union([], []) returns [] - √ union() throws an error - √ union(true, str) throws an error - √ union(false, true) throws an error - √ union(123, {}) throws an error - √ union([], {}) throws an error - √ union(undefined, null) throws an error - √ union([1, 2, 3], [4, 3, 2]) takes less than 2s to run - - Testing unionBy - - √ unionBy is a Function - √ Produces the appropriate results - - Testing unionWith - - √ unionWith is a Function - √ Produces the appropriate results - - Testing uniqueElements - - √ uniqueElements is a Function - √ uniqueElements([1, 2, 2, 3, 4, 4, 5]) returns [1,2,3,4,5] - √ uniqueElements([1, 23, 53]) returns [1, 23, 53] - √ uniqueElements([true, 0, 1, false, false, undefined, null, '']) returns [true, 0, 1, false, false, undefined, null, ''] - √ uniqueElements() returns [] - √ uniqueElements(null) returns [] - √ uniqueElements(undefined) returns [] - √ uniqueElements('strt') returns ['s', 't', 'r'] - √ uniqueElements(1, 1, 2543, 534, 5) throws an error - √ uniqueElements({}) throws an error - √ uniqueElements(true) throws an error - √ uniqueElements(false) throws an error - √ uniqueElements([true, 0, 1, false, false, undefined, null]) takes less than 2s to run - - Testing untildify - - √ untildify is a Function - - Testing unzip - - √ unzip is a Function - √ unzip([['a', 1, true], ['b', 2, false]]) equals [['a', 'b'], [1, 2], [true, false]] - √ unzip([['a', 1, true], ['b', 2]]) equals [['a', 'b'], [1, 2], [true]] - - Testing unzipWith - - √ unzipWith is a Function - √ unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)) equals [3, 30, 300] + ✔ RGBToHex is a Function + ✔ Converts the values of RGB components to a color code. Testing URLJoin - √ URLJoin is a Function - √ Returns proper URL - √ Returns proper URL + ✔ URLJoin is a Function + ✔ Returns proper URL + ✔ Returns proper URL Testing UUIDGeneratorBrowser - √ UUIDGeneratorBrowser is a Function + ✔ UUIDGeneratorBrowser is a Function Testing UUIDGeneratorNode - √ UUIDGeneratorNode is a Function + ✔ UUIDGeneratorNode is a Function + + Testing anagrams + + ✔ anagrams is a Function + ✔ Generates all anagrams of a string + ✔ Works for single-letter strings + ✔ Works for empty strings + + Testing arrayToHtmlList + + ✔ arrayToHtmlList is a Function + + Testing ary + + ✔ ary is a Function + ✔ Discards arguments with index >=n + + Testing atob + + ✔ atob is a Function + ✔ atob("Zm9vYmFy") equals "foobar" + ✔ atob("Z") returns "" + + Testing attempt + + ✔ attempt is a Function + ✔ Returns a value + ✔ Returns an error + + Testing average + + ✔ average is a Function + ✔ average(true) returns 0 + ✔ average(false) returns 1 + ✔ average(9, 1) returns 5 + ✔ average(153, 44, 55, 64, 71, 1122, 322774, 2232, 23423, 234, 3631) returns 32163.909090909092 + ✔ average(1, 2, 3) returns 2 + ✔ average(null) returns 0 + ✔ average(1, 2, 3) returns NaN + ✔ average(String) returns NaN + ✔ average({ a: 123}) returns NaN + ✔ average([undefined, 0, string]) returns NaN + ✔ head([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]) takes less than 2s to run + + Testing averageBy + + ✔ averageBy is a Function + ✔ Produces the right result with a function + ✔ Produces the right result with a property name + + Testing binarySearch + + ✔ binarySearch is a Function + ✔ Finds item in array + ✔ Returns -1 when not found + ✔ Works with empty arrays + ✔ Works for one element arrays + + Testing bind + + ✔ bind is a Function + ✔ Binds to an object context + + Testing bindAll + + ✔ bindAll is a Function + ✔ Binds to an object context + + Testing bindKey + + ✔ bindKey is a Function + ✔ Binds function to an object context + + Testing bottomVisible + + ✔ bottomVisible is a Function + + Testing btoa + + ✔ btoa is a Function + ✔ btoa("foobar") equals "Zm9vYmFy" + + Testing byteSize + + ✔ byteSize is a Function + ✔ Works for a single letter + ✔ Works for a common string + ✔ Works for emoji + + Testing call + + ✔ call is a Function + ✔ Calls function on given object + + Testing capitalize + + ✔ capitalize is a Function + ✔ Capitalizes the first letter of a string + ✔ Capitalizes the first letter of a string + ✔ Works with characters + ✔ Works with single character words + + Testing capitalizeEveryWord + + ✔ capitalizeEveryWord is a Function + ✔ Capitalizes the first letter of every word in a string + ✔ Works with characters + ✔ Works with one word string + + Testing castArray + + ✔ castArray is a Function + ✔ Works for single values + ✔ Works for arrays with one value + ✔ Works for arrays with multiple value + ✔ Works for strings + ✔ Works for objects + + Testing chainAsync + + ✔ chainAsync is a Function + + Testing chunk + + ✔ chunk is a Function + ✔ chunk([1, 2, 3, 4, 5], 2) returns [[1,2],[3,4],[5]] + ✔ chunk([]) returns [] + ✔ chunk(123) returns [] + ✔ chunk({ a: 123}) returns [] + ✔ chunk(string, 2) returns [ st, ri, ng ] + ✔ chunk() throws an error + ✔ chunk(undefined) throws an error + ✔ chunk(null) throws an error + ✔ chunk(This is a string, 2) takes less than 2s to run + + Testing clampNumber + + ✔ clampNumber is a Function + ✔ Clamps num within the inclusive range specified by the boundary values a and b + + Testing cleanObj + + ✔ cleanObj is a Function + ✔ Removes any properties except the ones specified from a JSON object + + Testing cloneRegExp + + ✔ cloneRegExp is a Function + ✔ Clones regular expressions properly + + Testing coalesce + + ✔ coalesce is a Function + ✔ Returns the first non-null/undefined argument + + Testing coalesceFactory + + ✔ coalesceFactory is a Function + ✔ Returns a customized coalesce function + + Testing collatz + + ✔ collatz is a Function + ✔ When n is even, divide by 2 + ✔ When n is odd, times by 3 and add 1 + ✔ Eventually reaches 1 + + Testing collectInto + + ✔ collectInto is a Function + + Testing colorize + + ✔ colorize is a Function + + Testing compact + + ✔ compact is a Function + ✔ Removes falsey values from an array + + Testing compose + + ✔ compose is a Function + ✔ Performs right-to-left function composition + + Testing composeRight + + ✔ composeRight is a Function + ✔ Performs left-to-right function composition + + Testing converge + + ✔ converge is a Function + ✔ Produces the average of the array + ✔ Produces the strange concatenation + + Testing copyToClipboard + + ✔ copyToClipboard is a Function + + Testing countBy + + ✔ countBy is a Function + ✔ Works for functions + ✔ Works for property names + + Testing countOccurrences + + ✔ countOccurrences is a Function + ✔ Counts the occurrences of a value in an array + + Testing countVowels + + ✔ countVowels is a Function + + Testing createElement + + ✔ createElement is a Function + + Testing createEventHub + + ✔ createEventHub is a Function + + Testing currentURL + + ✔ currentURL is a Function + + Testing curry + + ✔ curry is a Function + ✔ curries a Math.pow + ✔ curries a Math.min + + Testing debounce + + ✔ debounce is a Function + + Testing decapitalize + + ✔ decapitalize is a Function + ✔ Works with default parameter + ✔ Works with second parameter set to true + + Testing deepClone + + ✔ deepClone is a Function + ✔ Shallow cloning works + ✔ Deep cloning works + + Testing deepFlatten + + ✔ deepFlatten is a Function + ✔ Deep flattens an array + + Testing defaults + + ✔ defaults is a Function + + Testing defer + + ✔ defer is a Function + + Testing delay + + ✔ delay is a Function + + Testing detectDeviceType + + ✔ detectDeviceType is a Function + + Testing difference + + ✔ difference is a Function + ✔ Returns the difference between two arrays + + Testing differenceBy + + ✔ differenceBy is a Function + ✔ Works using a native function and numbers + ✔ Works with arrow function and objects + + Testing differenceWith + + ✔ differenceWith is a Function + ✔ Filters out all values from an array + + Testing digitize + + ✔ digitize is a Function + ✔ Converts a number to an array of digits + + Testing distance + + ✔ distance is a Function + ✔ Calculates the distance between two points + + Testing drop + + ✔ drop is a Function + ✔ Works without the last argument + ✔ Removes appropriate element count as specified + ✔ Empties array given a count greater than length + + Testing dropRight + + ✔ dropRight is a Function + ✔ Returns a new array with n elements removed from the right + ✔ Returns a new array with n elements removed from the right + ✔ Returns a new array with n elements removed from the right + + Testing dropRightWhile + + ✔ dropRightWhile is a Function + ✔ Removes elements from the end of an array until the passed function returns true. + + Testing dropWhile + + ✔ dropWhile is a Function + ✔ Removes elements in an array until the passed function returns true. + + Testing elementIsVisibleInViewport + + ✔ elementIsVisibleInViewport is a Function + + Testing elo + + ✔ elo is a Function + ✔ Standard 1v1s + ✔ should be equivalent + ✔ 4 player FFA, all same rank + + Testing equals + + ✔ equals is a Function + ✔ { a: [2, {e: 3}], b: [4], c: 'foo' } is equal to { a: [2, {e: 3}], b: [4], c: 'foo' } + ✔ [1,2,3] is equal to [1,2,3] + ✔ { a: [2, 3], b: [4] } is not equal to { a: [2, 3], b: [6] } + ✔ [1,2,3] is not equal to [1,2,4] + ✔ [1, 2, 3] should be equal to { 0: 1, 1: 2, 2: 3 }) - type is different, but their enumerable properties match. + + Testing escapeHTML + + ✔ escapeHTML is a Function + ✔ Escapes a string for use in HTML + + Testing escapeRegExp + + ✔ escapeRegExp is a Function + ✔ Escapes a string to use in a regular expression + + Testing everyNth + + ✔ everyNth is a Function + ✔ Returns every nth element in an array + + Testing extendHex + + ✔ extendHex is a Function + ✔ Extends a 3-digit color code to a 6-digit color code + ✔ Extends a 3-digit color code to a 6-digit color code + + Testing factorial + + ✔ factorial is a Function + ✔ Calculates the factorial of 720 + ✔ Calculates the factorial of 0 + ✔ Calculates the factorial of 1 + ✔ Calculates the factorial of 4 + ✔ Calculates the factorial of 10 + + Testing factors + + ✔ factors is a Function + + Testing fibonacci + + ✔ fibonacci is a Function + ✔ Generates an array, containing the Fibonacci sequence + + Testing fibonacciCountUntilNum + + ✔ fibonacciCountUntilNum is a Function + + Testing fibonacciUntilNum + + ✔ fibonacciUntilNum is a Function + + Testing filterNonUnique + + ✔ filterNonUnique is a Function + ✔ Filters out the non-unique values in an array + + Testing findKey + + ✔ findKey is a Function + ✔ Returns the appropriate key + + Testing findLast + + ✔ findLast is a Function + ✔ Finds last element for which the given function returns true + + Testing findLastIndex + + ✔ findLastIndex is a Function + ✔ Finds last index for which the given function returns true + + Testing findLastKey + + ✔ findLastKey is a Function + ✔ Returns the appropriate key + + Testing flatten + + ✔ flatten is a Function + ✔ Flattens an array + ✔ Flattens an array + + Testing flattenObject + + ✔ flattenObject is a Function + ✔ Flattens an object with the paths for keys + ✔ Works with arrays + + Testing flip + + ✔ flip is a Function + ✔ Flips argument order + + Testing forEachRight + + ✔ forEachRight is a Function + ✔ Iterates over the array in reverse + + Testing forOwn + + ✔ forOwn is a Function + ✔ Iterates over an element's key-value pairs + + Testing forOwnRight + + ✔ forOwnRight is a Function + ✔ Iterates over an element's key-value pairs in reverse + + Testing formatDuration + + ✔ formatDuration is a Function + ✔ Returns the human readable format of the given number of milliseconds + ✔ Returns the human readable format of the given number of milliseconds + + Testing fromCamelCase + + ✔ fromCamelCase is a Function + ✔ Converts a string from camelcase + ✔ Converts a string from camelcase + ✔ Converts a string from camelcase + + Testing functionName + + ✔ functionName is a Function + ✔ Works for native functions + ✔ Works for functions + ✔ Works for arrow functions + + Testing functions + + ✔ functions is a Function + ✔ Returns own methods + ✔ Returns own and inherited methods + + Testing gcd + + ✔ gcd is a Function + ✔ Calculates the greatest common divisor between two or more numbers/arrays + ✔ Calculates the greatest common divisor between two or more numbers/arrays + + Testing geometricProgression + + ✔ geometricProgression is a Function + ✔ Initializes an array containing the numbers in the specified range + ✔ Initializes an array containing the numbers in the specified range + ✔ Initializes an array containing the numbers in the specified range + + Testing get + + ✔ get is a Function + ✔ Retrieve a property indicated by the selector from an object. + + Testing getColonTimeFromDate + + ✔ getColonTimeFromDate is a Function + + Testing getDaysDiffBetweenDates + + ✔ getDaysDiffBetweenDates is a Function + ✔ Returns the difference in days between two dates + + Testing getMeridiemSuffixOfInteger + + ✔ getMeridiemSuffixOfInteger is a Function + + Testing getScrollPosition + + ✔ getScrollPosition is a Function + + Testing getStyle + + ✔ getStyle is a Function + + Testing getType + + ✔ getType is a Function + ✔ Returns the native type of a value + + Testing getURLParameters + + ✔ getURLParameters is a Function + ✔ Returns an object containing the parameters of the current URL + + Testing groupBy + + ✔ groupBy is a Function + ✔ Groups the elements of an array based on the given function + ✔ Groups the elements of an array based on the given function + + Testing hammingDistance + + ✔ hammingDistance is a Function + ✔ retuns hamming disance between 2 values + + Testing hasClass + + ✔ hasClass is a Function + + Testing hasFlags + + ✔ hasFlags is a Function + + Testing hashBrowser + + ✔ hashBrowser is a Function + + Testing hashNode + + ✔ hashNode is a Function + + Testing head + + ✔ head is a Function + ✔ head({ a: 1234}) returns undefined + ✔ head([1, 2, 3]) returns 1 + ✔ head({ 0: false}) returns false + ✔ head(String) returns S + ✔ head(null) throws an Error + ✔ head(undefined) throws an Error + ✔ head() throws an Error + ✔ head([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]) takes less than 2s to run + + Testing hexToRGB + + ✔ hexToRGB is a Function + ✔ Converts a color code to a rgb() or rgba() string + ✔ Converts a color code to a rgb() or rgba() string + ✔ Converts a color code to a rgb() or rgba() string + + Testing hide + + ✔ hide is a Function + + Testing howManyTimes + + ✔ howManyTimes is a Function + + Testing httpDelete + + ✔ httpDelete is a Function + + Testing httpGet + + ✔ httpGet is a Function + + Testing httpPost + + ✔ httpPost is a Function + + Testing httpPut + + ✔ httpPut is a Function + + Testing httpsRedirect + + ✔ httpsRedirect is a Function + + Testing inRange + + ✔ inRange is a Function + ✔ The given number falls within the given range + ✔ The given number falls within the given range + ✔ The given number does not falls within the given range + ✔ The given number does not falls within the given range + + Testing indexOfAll + + ✔ indexOfAll is a Function + ✔ Returns all indices of val in an array + ✔ Returns all indices of val in an array + + Testing initial + + ✔ initial is a Function + ✔ Returns all the elements of an array except the last one + + Testing initialize2DArray + + ✔ initialize2DArray is a Function + ✔ Initializes a 2D array of given width and height and value + + Testing initializeArrayWithRange + + ✔ initializeArrayWithRange is a Function + ✔ Initializes an array containing the numbers in the specified range + + Testing initializeArrayWithRangeRight + + ✔ initializeArrayWithRangeRight is a Function + + Testing initializeArrayWithValues + + ✔ initializeArrayWithValues is a Function + ✔ Initializes and fills an array with the specified values + + Testing intersection + + ✔ intersection is a Function + ✔ Returns a list of elements that exist in both arrays + + Testing intersectionBy + + ✔ intersectionBy is a Function + ✔ Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both + + Testing intersectionWith + + ✔ intersectionWith is a Function + ✔ Returns a list of elements that exist in both arrays, using a provided comparator function + + Testing invertKeyValues + + ✔ invertKeyValues is a Function + ✔ invertKeyValues({ a: 1, b: 2, c: 1 }) returns { 1: [ 'a', 'c' ], 2: [ 'b' ] } + ✔ invertKeyValues({ a: 1, b: 2, c: 1 }, value => 'group' + value) returns { group1: [ 'a', 'c' ], group2: [ 'b' ] } + + Testing is + + ✔ is is a Function + ✔ Works for arrays with data + ✔ Works for empty arrays + ✔ Works for arrays, not objects + ✔ Works for objects + ✔ Works for maps + ✔ Works for regular expressions + ✔ Works for sets + ✔ Works for weak maps + ✔ Works for weak sets + ✔ Works for strings - returns false for primitive + ✔ Works for strings - returns true when using constructor + ✔ Works for numbers - returns false for primitive + ✔ Works for numbers - returns true when using constructor + ✔ Works for booleans - returns false for primitive + ✔ Works for booleans - returns true when using constructor + ✔ Works for functions + + Testing isAbsoluteURL + + ✔ isAbsoluteURL is a Function + ✔ Given string is an absolute URL + ✔ Given string is an absolute URL + ✔ Given string is not an absolute URL + + Testing isArmstrongNumber + + ✔ isArmstrongNumber is a Function + + Testing isArray + + ✔ isArray is a Function + ✔ passed value is an array + ✔ passed value is not an array + + Testing isArrayBuffer + + ✔ isArrayBuffer is a Function + + Testing isArrayLike + + ✔ isArrayLike is a Function + ✔ Returns true for a string + ✔ Returns true for an array + ✔ Returns false for null + + Testing isBoolean + + ✔ isBoolean is a Function + ✔ passed value is not a boolean + ✔ passed value is not a boolean + + Testing isDivisible + + ✔ isDivisible is a Function + ✔ The number 6 is divisible by 3 + + Testing isEmpty + + ✔ isEmpty is a Function + ✔ Returns true for empty Map + ✔ Returns true for empty Set + ✔ Returns true for empty array + ✔ Returns true for empty object + ✔ Returns true for empty string + ✔ Returns false for non-empty array + ✔ Returns false for non-empty object + ✔ Returns false for non-empty string + ✔ Returns true - type is not considered a collection + ✔ Returns true - type is not considered a collection + + Testing isEven + + ✔ isEven is a Function + ✔ 4 is even number + ✔ undefined + + Testing isFunction + + ✔ isFunction is a Function + ✔ passed value is a function + ✔ passed value is not a function + + Testing isLowerCase + + ✔ isLowerCase is a Function + ✔ passed string is a lowercase + ✔ passed string is a lowercase + ✔ passed value is not a lowercase + + Testing isMap + + ✔ isMap is a Function + + Testing isNil + + ✔ isNil is a Function + ✔ Returns true for null + ✔ Returns true for undefined + ✔ Returns false for an empty string + + Testing isNull + + ✔ isNull is a Function + ✔ passed argument is a null + ✔ passed argument is a null + + Testing isNumber + + ✔ isNumber is a Function + ✔ passed argument is a number + ✔ passed argument is not a number + + Testing isObject + + ✔ isObject is a Function + ✔ isObject([1, 2, 3, 4]) is a object + ✔ isObject([]) is a object + ✔ isObject({ a:1 }) is a object + ✔ isObject(true) is not a object + + Testing isObjectLike + + ✔ isObjectLike is a Function + ✔ Returns true for an object + ✔ Returns true for an array + ✔ Returns false for a function + ✔ Returns false for null + + Testing isPlainObject + + ✔ isPlainObject is a Function + ✔ Returns true for a plain object + ✔ Returns false for a Map (example of non-plain object) + + Testing isPrime + + ✔ isPrime is a Function + ✔ passed number is a prime + + Testing isPrimitive + + ✔ isPrimitive is a Function + ✔ isPrimitive(null) is primitive + ✔ isPrimitive(undefined) is primitive + ✔ isPrimitive(string) is primitive + ✔ isPrimitive(true) is primitive + ✔ isPrimitive(50) is primitive + ✔ isPrimitive('Hello') is primitive + ✔ isPrimitive(false) is primitive + ✔ isPrimitive(Symbol()) is primitive + ✔ isPrimitive([1, 2, 3]) is not primitive + ✔ isPrimitive({ a: 123 }) is not primitive + ✔ isPrimitive({ a: 123 }) takes less than 2s to run + + Testing isPromiseLike + + ✔ isPromiseLike is a Function + ✔ Returns true for a promise-like object + ✔ Returns false for null + ✔ Returns false for an empty object + + Testing isRegExp + + ✔ isRegExp is a Function + + Testing isSet + + ✔ isSet is a Function + + Testing isSorted + + ✔ isSorted is a Function + ✔ Array is sorted in ascending order + ✔ Array is sorted in descending order + ✔ Array is not sorted, direction changed in array + + Testing isString + + ✔ isString is a Function + ✔ foo is a string + ✔ "10" is a string + ✔ Empty string is a string + ✔ 10 is not a string + ✔ true is not string + + Testing isSymbol + + ✔ isSymbol is a Function + ✔ Checks if the given argument is a symbol + + Testing isTravisCI + + ✔ isTravisCI is a Function + ✔ Running on Travis, correctly evaluates + + Testing isTypedArray + + ✔ isTypedArray is a Function + + Testing isUndefined + + ✔ isUndefined is a Function + ✔ Returns true for undefined + + Testing isUpperCase + + ✔ isUpperCase is a Function + ✔ ABC is all upper case + ✔ abc is not all upper case + ✔ A3@$ is all uppercase + + Testing isValidJSON + + ✔ isValidJSON is a Function + ✔ {"name":"Adam","age":20} is a valid JSON + ✔ {"name":"Adam",age:"20"} is not a valid JSON + ✔ null is a valid JSON + + Testing isWeakMap + + ✔ isWeakMap is a Function + + Testing isWeakSet + + ✔ isWeakSet is a Function + + Testing join + + ✔ join is a Function + ✔ Joins all elements of an array into a string and returns this string + ✔ Joins all elements of an array into a string and returns this string + ✔ Joins all elements of an array into a string and returns this string + + Testing last + + ✔ last is a Function + ✔ last({ a: 1234}) returns undefined + ✔ last([1, 2, 3]) returns 3 + ✔ last({ 0: false}) returns undefined + ✔ last(String) returns g + ✔ last(null) throws an Error + ✔ last(undefined) throws an Error + ✔ last() throws an Error + ✔ last([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]) takes less than 2s to run + + Testing lcm + + ✔ lcm is a Function + ✔ Returns the least common multiple of two or more numbers. + ✔ Returns the least common multiple of two or more numbers. + + Testing longestItem + + ✔ longestItem is a Function + ✔ Returns the longest object + + Testing lowercaseKeys + + ✔ lowercaseKeys is a Function + ✔ Lowercases object keys + ✔ Does not mutate original object + + Testing luhnCheck + + ✔ luhnCheck is a Function + ✔ validates identification number + ✔ validates identification number + ✔ validates identification number + + Testing mapKeys + + ✔ mapKeys is a Function + ✔ Maps keys + + Testing mapObject + + ✔ mapObject is a Function + ✔ mapObject([1, 2, 3], a => a * a) returns { 1: 1, 2: 4, 3: 9 } + ✔ mapObject([1, 2, 3, 4], (a, b) => b - a) returns { 1: -1, 2: -1, 3: -1, 4: -1 } + ✔ mapObject([1, 2, 3, 4], (a, b) => a - b) returns { 1: 1, 2: 1, 3: 1, 4: 1 } + + Testing mapValues + + ✔ mapValues is a Function + ✔ Maps values + + Testing mask + + ✔ mask is a Function + ✔ Replaces all but the last num of characters with the specified mask character + ✔ Replaces all but the last num of characters with the specified mask character + ✔ Replaces all but the last num of characters with the specified mask character + + Testing matches + + ✔ matches is a Function + ✔ Matches returns true for two similar objects + ✔ Matches returns false for two non-similar objects + + Testing matchesWith + + ✔ matchesWith is a Function + ✔ Returns true for two objects with similar values, based on the provided function + + Testing maxBy + + ✔ maxBy is a Function + ✔ Produces the right result with a function + ✔ Produces the right result with a property name + + Testing maxN + + ✔ maxN is a Function + ✔ Returns the n maximum elements from the provided array + ✔ Returns the n maximum elements from the provided array + + Testing median + + ✔ median is a Function + ✔ Returns the median of an array of numbers + ✔ Returns the median of an array of numbers + + Testing memoize + + ✔ memoize is a Function + ✔ Function works properly + ✔ Function works properly + ✔ Cache stores values + + Testing merge + + ✔ merge is a Function + ✔ Merges two objects + + Testing minBy + + ✔ minBy is a Function + ✔ Produces the right result with a function + ✔ Produces the right result with a property name + + Testing minN + + ✔ minN is a Function + ✔ Returns the n minimum elements from the provided array + ✔ Returns the n minimum elements from the provided array + + Testing negate + + ✔ negate is a Function + ✔ Negates a predicate function + + Testing nthArg + + ✔ nthArg is a Function + ✔ Returns the nth argument + ✔ Returns undefined if arguments too few + ✔ Works for negative values + + Testing nthElement + + ✔ nthElement is a Function + ✔ Returns the nth element of an array. + ✔ Returns the nth element of an array. + + Testing objectFromPairs + + ✔ objectFromPairs is a Function + ✔ Creates an object from the given key-value pairs. + + Testing objectToPairs + + ✔ objectToPairs is a Function + ✔ Creates an array of key-value pair arrays from an object. + + Testing observeMutations + + ✔ observeMutations is a Function + + Testing off + + ✔ off is a Function + + Testing omit + + ✔ omit is a Function + ✔ Omits the key-value pairs corresponding to the given keys from an object + + Testing omitBy + + ✔ omitBy is a Function + ✔ Creates an object composed of the properties the given function returns falsey for + + Testing on + + ✔ on is a Function + + Testing onUserInputChange + + ✔ onUserInputChange is a Function + + Testing once + + ✔ once is a Function + + Testing orderBy + + ✔ orderBy is a Function + ✔ Returns a sorted array of objects ordered by properties and orders. + ✔ Returns a sorted array of objects ordered by properties and orders. + + Testing over + + ✔ over is a Function + ✔ Applies given functions over multiple arguments + + Testing overArgs + + ✔ overArgs is a Function + ✔ Invokes the provided function with its arguments transformed + + Testing palindrome + + ✔ palindrome is a Function + ✔ Given string is a palindrome + ✔ Given string is not a palindrome + + Testing parseCookie + + ✔ parseCookie is a Function + ✔ Parses the cookie + + Testing partial + + ✔ partial is a Function + ✔ Prepends arguments + + Testing partialRight + + ✔ partialRight is a Function + ✔ Appends arguments + + Testing partition + + ✔ partition is a Function + ✔ Groups the elements into two arrays, depending on the provided function's truthiness for each element. + + Testing percentile + + ✔ percentile is a Function + ✔ Uses the percentile formula to calculate how many numbers in the given array are less or equal to the given value. + + Testing pick + + ✔ pick is a Function + ✔ Picks the key-value pairs corresponding to the given keys from an object. + + Testing pickBy + + ✔ pickBy is a Function + ✔ Creates an object composed of the properties the given function returns truthy for. + + Testing pipeAsyncFunctions + + ✔ pipeAsyncFunctions is a Function + ✔ Produces the appropriate hash + ✔ pipeAsyncFunctions result should be 15 + + Testing pipeFunctions + + ✔ pipeFunctions is a Function + ✔ Performs left-to-right function composition + + Testing pluralize + + ✔ pluralize is a Function + ✔ Produces the plural of the word + ✔ Produces the singular of the word + ✔ Produces the plural of the word + ✔ Prodices the defined plural of the word + ✔ Works with a dictionary + + Testing powerset + + ✔ powerset is a Function + ✔ Returns the powerset of a given array of numbers. + + Testing prettyBytes + + ✔ prettyBytes is a Function + ✔ Converts a number in bytes to a human-readable string. + ✔ Converts a number in bytes to a human-readable string. + ✔ Converts a number in bytes to a human-readable string. + + Testing primes + + ✔ primes is a Function + ✔ Generates primes up to a given number, using the Sieve of Eratosthenes. + + Testing promisify + + ✔ promisify is a Function + + Testing pull + + ✔ pull is a Function + ✔ Pulls the specified values + + Testing pullAtIndex + + ✔ pullAtIndex is a Function + ✔ Pulls the given values + ✔ Pulls the given values + + Testing pullAtValue + + ✔ pullAtValue is a Function + ✔ Pulls the specified values + ✔ Pulls the specified values + + Testing pullBy + + ✔ pullBy is a Function + ✔ Pulls the specified values + + Testing quickSort + + ✔ quickSort is a Function + ✔ quickSort([5, 6, 4, 3, 1, 2]) returns [1, 2, 3, 4, 5, 6] + ✔ quickSort([-1, 0, -2]) returns [-2, -1, 0] + ✔ quickSort() throws an error + ✔ quickSort(123) throws an error + ✔ quickSort({ 234: string}) throws an error + ✔ quickSort(null) throws an error + ✔ quickSort(undefined) throws an error + ✔ quickSort([11, 1, 324, 23232, -1, 53, 2, 524, 32, 13, 156, 133, 62, 12, 4]) takes less than 2s to run + + Testing randomHexColorCode + + ✔ randomHexColorCode is a Function + ✔ should be equal + + Testing randomIntArrayInRange + + ✔ randomIntArrayInRange is a Function + + Testing randomIntegerInRange + + ✔ randomIntegerInRange is a Function + ✔ The returned value is a Integer + ✔ The returned value lies between provied lowerLimit and upperLimit (both inclusive). + + Testing randomNumberInRange + + ✔ randomNumberInRange is a Function + + Testing readFileLines + + ✔ readFileLines is a Function + + Testing rearg + + ✔ rearg is a Function + ✔ Reorders arguments in invoked function + + Testing redirect + + ✔ redirect is a Function + + Testing reduceSuccessive + + ✔ reduceSuccessive is a Function + ✔ Returns the array of successively reduced values + + Testing reduceWhich + + ✔ reduceWhich is a Function + ✔ Returns the minimum of an array + ✔ Returns the maximum of an array + ✔ Returns the object with the minimum specified value in an array + + Testing reducedFilter + + ✔ reducedFilter is a Function + ✔ Filter an array of objects based on a condition while also filtering out unspecified keys. + + Testing remove + + ✔ remove is a Function + ✔ Removes elements from an array for which the given function returns false + + Testing removeNonASCII + + ✔ removeNonASCII is a Function + ✔ Removes non-ASCII characters + + Testing removeVowels + + ✔ removeVowels is a Function + + Testing reverseString + + ✔ reverseString is a Function + ✔ Reverses a string. + + Testing round + + ✔ round is a Function + ✔ round(1.005, 2) returns 1.01 + ✔ round(123.3423345345345345344, 11) returns 123.34233453453 + ✔ round(3.342, 11) returns 3.342 + ✔ round(1.005) returns 1 + ✔ round([1.005, 2]) returns NaN + ✔ round(string) returns NaN + ✔ round() returns NaN + ✔ round(132, 413, 4134) returns NaN + ✔ round({a: 132}, 413) returns NaN + ✔ round(123.3423345345345345344, 11) takes less than 2s to run + + Testing runAsync + + ✔ runAsync is a Function + + Testing runPromisesInSeries + + ✔ runPromisesInSeries is a Function + + Testing sample + + ✔ sample is a Function + + Testing sampleSize + + ✔ sampleSize is a Function + + Testing scrollToTop + + ✔ scrollToTop is a Function + + Testing sdbm + + ✔ sdbm is a Function + ✔ Hashes the input string into a whole number. + + Testing serializeCookie + + ✔ serializeCookie is a Function + ✔ Serializes the cookie + + Testing setStyle + + ✔ setStyle is a Function + + Testing shallowClone + + ✔ shallowClone is a Function + ✔ Shallow cloning works + ✔ Does not clone deeply + + Testing show + + ✔ show is a Function + + Testing shuffle + + ✔ shuffle is a Function + + Testing similarity + + ✔ similarity is a Function + ✔ Returns an array of elements that appear in both arrays. + + Testing size + + ✔ size is a Function + ✔ Get size of arrays, objects or strings. + ✔ Get size of arrays, objects or strings. + + Testing sleep + + ✔ sleep is a Function + + Testing solveRPN + + ✔ solveRPN is a Function + + Testing sortCharactersInString + + ✔ sortCharactersInString is a Function + ✔ Alphabetically sorts the characters in a string. + + Testing sortedIndex + + ✔ sortedIndex is a Function + ✔ Returns the lowest index at which value should be inserted into array in order to maintain its sort order. + ✔ Returns the lowest index at which value should be inserted into array in order to maintain its sort order. + + Testing sortedIndexBy + + ✔ sortedIndexBy is a Function + ✔ Returns the lowest index to insert the element without messing up the list order + + Testing sortedLastIndex + + ✔ sortedLastIndex is a Function + ✔ Returns the highest index to insert the element without messing up the list order + + Testing sortedLastIndexBy + + ✔ sortedLastIndexBy is a Function + ✔ Returns the highest index to insert the element without messing up the list order + + Testing speechSynthesis + + ✔ speechSynthesis is a Function + + Testing splitLines + + ✔ splitLines is a Function + ✔ Splits a multiline string into an array of lines. + + Testing spreadOver + + ✔ spreadOver is a Function + ✔ Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function. + + Testing standardDeviation + + ✔ standardDeviation is a Function + ✔ Returns the standard deviation of an array of numbers + ✔ Returns the standard deviation of an array of numbers + + Testing stripHTMLTags + + ✔ stripHTMLTags is a Function + ✔ Removes HTML tags + + Testing sum + + ✔ sum is a Function + ✔ Returns the sum of two or more numbers/arrays. + + Testing sumBy + + ✔ sumBy is a Function + + Testing sumPower + + ✔ sumPower is a Function + ✔ Returns the sum of the powers of all the numbers from start to end + ✔ Returns the sum of the powers of all the numbers from start to end + ✔ Returns the sum of the powers of all the numbers from start to end + + Testing symmetricDifference + + ✔ symmetricDifference is a Function + ✔ Returns the symmetric difference between two arrays. + + Testing symmetricDifferenceBy + + ✔ symmetricDifferenceBy is a Function + ✔ Returns the symmetric difference between two arrays, after applying the provided function to each array element of both + + Testing symmetricDifferenceWith + + ✔ symmetricDifferenceWith is a Function + ✔ Returns the symmetric difference between two arrays, using a provided function as a comparator + + Testing tail + + ✔ tail is a Function + ✔ Returns tail + ✔ Returns tail + + Testing take + + ✔ take is a Function + ✔ Returns an array with n elements removed from the beginning. + ✔ Returns an array with n elements removed from the beginning. + + Testing takeRight + + ✔ takeRight is a Function + ✔ Returns an array with n elements removed from the end + ✔ Returns an array with n elements removed from the end + + Testing takeRightWhile + + ✔ takeRightWhile is a Function + ✔ Removes elements until the function returns true + + Testing takeWhile + + ✔ takeWhile is a Function + ✔ Removes elements until the function returns true + + Testing throttle + + ✔ throttle is a Function + + Testing timeTaken + + ✔ timeTaken is a Function + + Testing times + + ✔ times is a Function + ✔ Runs a function the specified amount of times + + Testing toCamelCase + + ✔ toCamelCase is a Function + ✔ toCamelCase('some_database_field_name') returns someDatabaseFieldName + ✔ toCamelCase('Some label that needs to be camelized') returns someLabelThatNeedsToBeCamelized + ✔ toCamelCase('some-javascript-property') return someJavascriptProperty + ✔ toCamelCase('some-mixed_string with spaces_underscores-and-hyphens') returns someMixedStringWithSpacesUnderscoresAndHyphens + ✔ toCamelCase() throws a error + ✔ toCamelCase([]) throws a error + ✔ toCamelCase({}) throws a error + ✔ toCamelCase(123) throws a error + ✔ toCamelCase(some-mixed_string with spaces_underscores-and-hyphens) takes less than 2s to run + + Testing toCurrency + + ✔ toCurrency is a Function + ✔ currency: Euro | currencyLangFormat: Local + ✔ currency: US Dollar | currencyLangFormat: English (United States) + ✔ currency: Japanese Yen | currencyLangFormat: Local + + Testing toDecimalMark + + ✔ toDecimalMark is a Function + ✔ convert a float-point arithmetic to the Decimal mark form + + Testing toKebabCase + + ✔ toKebabCase is a Function + ✔ toKebabCase('camelCase') returns camel-case + ✔ toKebabCase('some text') returns some-text + ✔ toKebabCase('some-mixed-string With spaces-underscores-and-hyphens') returns some-mixed-string-with-spaces-underscores-and-hyphens + ✔ toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') returns i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-some-xml-and-html + ✔ toKebabCase() return undefined + ✔ toKebabCase([]) throws an error + ✔ toKebabCase({}) throws an error + ✔ toKebabCase(123) throws an error + ✔ toKebabCase(IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML) takes less than 2s to run + + Testing toOrdinalSuffix + + ✔ toOrdinalSuffix is a Function + ✔ Adds an ordinal suffix to a number + ✔ Adds an ordinal suffix to a number + ✔ Adds an ordinal suffix to a number + ✔ Adds an ordinal suffix to a number + + Testing toSafeInteger + + ✔ toSafeInteger is a Function + ✔ Number(toSafeInteger(3.2)) is a number + ✔ Converts a value to a safe integer + ✔ toSafeInteger('4.2') returns 4 + ✔ toSafeInteger(4.6) returns 5 + ✔ toSafeInteger([]) returns 0 + ✔ isNaN(toSafeInteger([1.5, 3124])) is true + ✔ isNaN(toSafeInteger('string')) is true + ✔ isNaN(toSafeInteger({})) is true + ✔ isNaN(toSafeInteger()) is true + ✔ toSafeInteger(Infinity) returns 9007199254740991 + ✔ toSafeInteger(3.2) takes less than 2s to run + + Testing toSnakeCase + + ✔ toSnakeCase is a Function + ✔ toSnakeCase('camelCase') returns camel_case + ✔ toSnakeCase('some text') returns some_text + ✔ toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens') returns some_mixed_string_with_spaces_underscores_and_hyphens + ✔ toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') returns i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html + ✔ toSnakeCase() returns undefined + ✔ toSnakeCase([]) throws an error + ✔ toSnakeCase({}) throws an error + ✔ toSnakeCase(123) throws an error + ✔ toSnakeCase(IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML) takes less than 2s to run + + Testing toggleClass + + ✔ toggleClass is a Function + + Testing tomorrow + + ✔ tomorrow is a Function + + Testing transform + + ✔ transform is a Function + ✔ Transforms an object + + Testing truncateString + + ✔ truncateString is a Function + ✔ Truncates a "boomerang" up to a specified length. + + Testing truthCheckCollection + + ✔ truthCheckCollection is a Function + ✔ second argument is truthy on all elements of a collection + + Testing unary + + ✔ unary is a Function + ✔ Discards arguments after the first one + + Testing unescapeHTML + + ✔ unescapeHTML is a Function + ✔ Unescapes escaped HTML characters. + + Testing unflattenObject + + ✔ unflattenObject is a Function + ✔ Unflattens an object with the paths for keys + + Testing unfold + + ✔ unfold is a Function + ✔ Works with a given function, producing an array + + Testing union + + ✔ union is a Function + ✔ union([1, 2, 3], [4, 3, 2]) returns [1, 2, 3, 4] + ✔ union('str', 'asd') returns [ 's', 't', 'r', 'a', 'd' ] + ✔ union([[], {}], [1, 2, 3]) returns [[], {}, 1, 2, 3] + ✔ union([], []) returns [] + ✔ union() throws an error + ✔ union(true, str) throws an error + ✔ union(false, true) throws an error + ✔ union(123, {}) throws an error + ✔ union([], {}) throws an error + ✔ union(undefined, null) throws an error + ✔ union([1, 2, 3], [4, 3, 2]) takes less than 2s to run + + Testing unionBy + + ✔ unionBy is a Function + ✔ Produces the appropriate results + + Testing unionWith + + ✔ unionWith is a Function + ✔ Produces the appropriate results + + Testing uniqueElements + + ✔ uniqueElements is a Function + ✔ uniqueElements([1, 2, 2, 3, 4, 4, 5]) returns [1,2,3,4,5] + ✔ uniqueElements([1, 23, 53]) returns [1, 23, 53] + ✔ uniqueElements([true, 0, 1, false, false, undefined, null, '']) returns [true, 0, 1, false, false, undefined, null, ''] + ✔ uniqueElements() returns [] + ✔ uniqueElements(null) returns [] + ✔ uniqueElements(undefined) returns [] + ✔ uniqueElements('strt') returns ['s', 't', 'r'] + ✔ uniqueElements(1, 1, 2543, 534, 5) throws an error + ✔ uniqueElements({}) throws an error + ✔ uniqueElements(true) throws an error + ✔ uniqueElements(false) throws an error + ✔ uniqueElements([true, 0, 1, false, false, undefined, null]) takes less than 2s to run + + Testing untildify + + ✔ untildify is a Function + + Testing unzip + + ✔ unzip is a Function + ✔ unzip([['a', 1, true], ['b', 2, false]]) equals [['a', 'b'], [1, 2], [true, false]] + ✔ unzip([['a', 1, true], ['b', 2]]) equals [['a', 'b'], [1, 2], [true]] + + Testing unzipWith + + ✔ unzipWith is a Function + ✔ unzipWith([[1, 10, 100], [2, 20, 200]], (...args) => args.reduce((acc, v) => acc + v, 0)) equals [3, 30, 300] Testing validateNumber - √ validateNumber is a Function - √ validateNumber(9) returns true - √ validateNumber(234asd.slice(0, 2)) returns true - √ validateNumber(1232) returns true - √ validateNumber(1232 + 13423) returns true - √ validateNumber(1232 * 2342 * 123) returns true - √ validateNumber(1232.23423536) returns true - √ validateNumber(234asd) returns false - √ validateNumber(e234d) returns false - √ validateNumber(false) returns false - √ validateNumber(true) returns false - √ validateNumber(null) returns false - √ validateNumber(123 * asd) returns false + ✔ validateNumber is a Function + ✔ validateNumber(9) returns true + ✔ validateNumber(234asd.slice(0, 2)) returns true + ✔ validateNumber(1232) returns true + ✔ validateNumber(1232 + 13423) returns true + ✔ validateNumber(1232 * 2342 * 123) returns true + ✔ validateNumber(1232.23423536) returns true + ✔ validateNumber(234asd) returns false + ✔ validateNumber(e234d) returns false + ✔ validateNumber(false) returns false + ✔ validateNumber(true) returns false + ✔ validateNumber(null) returns false + ✔ validateNumber(123 * asd) returns false Testing without - √ without is a Function - √ without([2, 1, 2, 3], 1, 2) returns [3] - √ without([]) returns [] - √ without([3, 1, true, '3', true], '3', true) returns [3, 1] - √ without('string'.split(''), 's', 't', 'g') returns ['r', 'i', 'n'] - √ without() throws an error - √ without(null) throws an error - √ without(undefined) throws an error - √ without() throws an error - √ without({}) throws an error + ✔ without is a Function + ✔ without([2, 1, 2, 3], 1, 2) returns [3] + ✔ without([]) returns [] + ✔ without([3, 1, true, '3', true], '3', true) returns [3, 1] + ✔ without('string'.split(''), 's', 't', 'g') returns ['r', 'i', 'n'] + ✔ without() throws an error + ✔ without(null) throws an error + ✔ without(undefined) throws an error + ✔ without() throws an error + ✔ without({}) throws an error Testing words - √ words is a Function - √ words('I love javaScript!!') returns [I, love, javaScript] - √ words('python, javaScript & coffee') returns [python, javaScript, coffee] - √ words(I love javaScript!!) returns an array - √ words() throws a error - √ words(null) throws a error - √ words(undefined) throws a error - √ words({}) throws a error - √ words([]) throws a error - √ words(1234) throws a error + ✔ words is a Function + ✔ words('I love javaScript!!') returns [I, love, javaScript] + ✔ words('python, javaScript & coffee') returns [python, javaScript, coffee] + ✔ words(I love javaScript!!) returns an array + ✔ words() throws a error + ✔ words(null) throws a error + ✔ words(undefined) throws a error + ✔ words({}) throws a error + ✔ words([]) throws a error + ✔ words(1234) throws a error Testing xProd - √ xProd is a Function - √ xProd([1, 2], ['a', 'b']) returns [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] + ✔ xProd is a Function + ✔ xProd([1, 2], ['a', 'b']) returns [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] Testing yesNo - √ yesNo is a Function - √ yesNo(Y) returns true - √ yesNo(yes) returns true - √ yesNo(foo, true) returns true - √ yesNo(No) returns false - √ yesNo() returns false - √ yesNo(null) returns false - √ yesNo(undefined) returns false - √ yesNo([123, null]) returns false - √ yesNo([Yes, No]) returns false - √ yesNo({ 2: Yes }) returns false - √ yesNo([Yes, No], true) returns true - √ yesNo({ 2: Yes }, true) returns true + ✔ yesNo is a Function + ✔ yesNo(Y) returns true + ✔ yesNo(yes) returns true + ✔ yesNo(foo, true) returns true + ✔ yesNo(No) returns false + ✔ yesNo() returns false + ✔ yesNo(null) returns false + ✔ yesNo(undefined) returns false + ✔ yesNo([123, null]) returns false + ✔ yesNo([Yes, No]) returns false + ✔ yesNo({ 2: Yes }) returns false + ✔ yesNo([Yes, No], true) returns true + ✔ yesNo({ 2: Yes }, true) returns true Testing zip - √ zip is a Function - √ zip([a, b], [1, 2], [true, false]) returns [[a, 1, true], [b, 2, false]] - √ zip([a], [1, 2], [true, false]) returns [[a, 1, true], [undefined, 2, false]] - √ zip([]) returns [] - √ zip(123) returns [] - √ zip([a, b], [1, 2], [true, false]) returns an Array - √ zip([a], [1, 2], [true, false]) returns an Array - √ zip(null) throws an error - √ zip(undefined) throws an error + ✔ zip is a Function + ✔ zip([a, b], [1, 2], [true, false]) returns [[a, 1, true], [b, 2, false]] + ✔ zip([a], [1, 2], [true, false]) returns [[a, 1, true], [undefined, 2, false]] + ✔ zip([]) returns [] + ✔ zip(123) returns [] + ✔ zip([a, b], [1, 2], [true, false]) returns an Array + ✔ zip([a], [1, 2], [true, false]) returns an Array + ✔ zip(null) throws an error + ✔ zip(undefined) throws an error Testing zipObject - √ zipObject is a Function - √ zipObject([a, b, c], [1, 2]) returns {a: 1, b: 2, c: undefined} - √ zipObject([a, b], [1, 2, 3]) returns {a: 1, b: 2} - √ zipObject([a, b, c], string) returns { a: s, b: t, c: r } - √ zipObject([a], string) returns { a: s } - √ zipObject() throws an error - √ zipObject([string], null) throws an error - √ zipObject(null, [1]) throws an error - √ zipObject(string) throws an error - √ zipObject(test, string) throws an error + ✔ zipObject is a Function + ✔ zipObject([a, b, c], [1, 2]) returns {a: 1, b: 2, c: undefined} + ✔ zipObject([a, b], [1, 2, 3]) returns {a: 1, b: 2} + ✔ zipObject([a, b, c], string) returns { a: s, b: t, c: r } + ✔ zipObject([a], string) returns { a: s } + ✔ zipObject() throws an error + ✔ zipObject([string], null) throws an error + ✔ zipObject(null, [1]) throws an error + ✔ zipObject(string) throws an error + ✔ zipObject(test, string) throws an error Testing zipWith - √ zipWith is a Function - √ Sends a GET request - √ Sends a POST request - √ Works with multiple promises + ✔ zipWith is a Function + ✔ Sends a GET request + ✔ Sends a POST request + ✔ Works with multiple promises - total: 856 - passing: 856 - duration: 2.4s + total: 860 + passing: 860 + duration: 2.3s From b9caf23741b044cd17a3d7032a809ab9d6b17fba Mon Sep 17 00:00:00 2001 From: Dave Henton Date: Thu, 8 Feb 2018 15:41:26 -0800 Subject: [PATCH 08/35] Update README.md --- README.md | 16036 ++++++++++++++++++++++++++-------------------------- 1 file changed, 8018 insertions(+), 8018 deletions(-) diff --git a/README.md b/README.md index 39fc8c4fa..d751a8599 100644 --- a/README.md +++ b/README.md @@ -1,8054 +1,8054 @@ -![Logo](/logo.png) - -# 30 seconds of code - -[![License](https://img.shields.io/badge/license-CC0--1.0-blue.svg)](https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE) [![npm Downloads](https://img.shields.io/npm/dt/30-seconds-of-code.svg)](https://www.npmjs.com/package/30-seconds-of-code) [![npm Version](https://img.shields.io/npm/v/30-seconds-of-code.svg)](https://www.npmjs.com/package/30-seconds-of-code) [![Gitter chat](https://img.shields.io/badge/chat-on%20gitter-4FB999.svg)](https://gitter.im/30-seconds-of-code/Lobby) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Travis Build](https://travis-ci.org/Chalarangelo/30-seconds-of-code.svg?branch=master)](https://travis-ci.org/Chalarangelo/30-seconds-of-code) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/207ea6fa2c204ccda61dc3047986e144)](https://www.codacy.com/app/Chalarangelo/30-seconds-of-code?utm_source=github.com&utm_medium=referral&utm_content=Chalarangelo/30-seconds-of-code&utm_campaign=badger) [![Maintainability](https://api.codeclimate.com/v1/badges/e9020d1c963a91c0c8a2/maintainability)](https://codeclimate.com/github/Chalarangelo/30-seconds-of-code/maintainability) [![Insight.io](https://img.shields.io/badge/insight.io-Ready-brightgreen.svg)](https://insight.io/github.com/Chalarangelo/30-seconds-of-code/tree/master/?source=0) [![js-semistandard-style](https://img.shields.io/badge/code%20style-semistandard-brightgreen.svg)](https://github.com/Flet/semistandard) [![ProductHunt](https://img.shields.io/badge/producthunt-vote-orange.svg)](https://www.producthunt.com/posts/30-seconds-of-code) - - -> Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. - - -- Use Ctrl + F or command + F to search for a snippet. -- Contributions welcome, please read the [contribution guide](CONTRIBUTING.md). -- Snippets are written in ES6, use the [Babel transpiler](https://babeljs.io/) to ensure backwards-compatibility. -- You can import these snippets into your text editor of choice (VSCode, Atom, Sublime) using the files found in [this repo](https://github.com/Rob-Rychs/30-seconds-of-code-texteditorsnippets). -- You can import these snippets into Alfred 3, using [this file](https://github.com/lslvxy/30-seconds-of-code-alfredsnippets). - -#### Package - -⚠️ **WARNING:** Snippets are not production ready. - -You can find a package with all the snippets on [npm](https://www.npmjs.com/package/30-seconds-of-code). - -```bash -# With npm -npm install 30-seconds-of-code - -# With yarn -yarn add 30-seconds-of-code -``` - -CDN links -- [ES2017 Full (UMD)](https://unpkg.com/30-seconds-of-code) -- [ES5 Minified (UMD)](https://unpkg.com/30-seconds-of-code/dist/_30s.es5.min.js) - -
-Details - -**Browser** - -> IMPORTANT: replace the `src` with the full version link and desired target spec (such as ES5 minified)): - -```html - - -``` - -**Node** - -```js -// CommonJS -const _30s = require('30-seconds-of-code'); -_30s.average(1, 2, 3); - -// ES Modules -import _30s from '30-seconds-of-code'; -_30s.average(1, 2, 3); -``` - -To import snippets directly: - -```js -// CommonJS -const { average } = require('30-seconds-of-code'); -average(1, 2, 3); - -// ES Modules -import { average } from '30-seconds-of-code'; -average(1, 2, 3); -``` -
- -## Table of Contents - -### 🔌 Adapter - -
-View contents - -* [`ary`](#ary) -* [`call`](#call) -* [`collectInto`](#collectinto) -* [`flip`](#flip) -* [`over`](#over) -* [`overArgs`](#overargs) -* [`pipeAsyncFunctions`](#pipeasyncfunctions) -* [`pipeFunctions`](#pipefunctions) -* [`promisify`](#promisify) -* [`rearg`](#rearg) -* [`spreadOver`](#spreadover) -* [`unary`](#unary) - -
- -### 📚 Array - -
-View contents - -* [`chunk`](#chunk) -* [`compact`](#compact) -* [`countBy`](#countby) -* [`countOccurrences`](#countoccurrences) -* [`deepFlatten`](#deepflatten) -* [`difference`](#difference) -* [`differenceBy`](#differenceby) -* [`differenceWith`](#differencewith) -* [`drop`](#drop) -* [`dropRight`](#dropright) -* [`dropRightWhile`](#droprightwhile) -* [`dropWhile`](#dropwhile) -* [`everyNth`](#everynth) -* [`filterNonUnique`](#filternonunique) -* [`findLast`](#findlast) -* [`findLastIndex`](#findlastindex) -* [`flatten`](#flatten) -* [`forEachRight`](#foreachright) -* [`groupBy`](#groupby) -* [`head`](#head) -* [`indexOfAll`](#indexofall) -* [`initial`](#initial) -* [`initialize2DArray`](#initialize2darray) -* [`initializeArrayWithRange`](#initializearraywithrange) -* [`initializeArrayWithRangeRight`](#initializearraywithrangeright) -* [`initializeArrayWithValues`](#initializearraywithvalues) -* [`intersection`](#intersection) -* [`intersectionBy`](#intersectionby) -* [`intersectionWith`](#intersectionwith) -* [`isSorted`](#issorted) -* [`join`](#join) -* [`last`](#last) -* [`longestItem`](#longestitem) -* [`mapObject`](#mapobject-) -* [`maxN`](#maxn) -* [`minN`](#minn) -* [`nthElement`](#nthelement) -* [`partition`](#partition) -* [`pull`](#pull) -* [`pullAtIndex`](#pullatindex) -* [`pullAtValue`](#pullatvalue) -* [`pullBy`](#pullby-) -* [`reducedFilter`](#reducedfilter) -* [`reduceSuccessive`](#reducesuccessive) -* [`reduceWhich`](#reducewhich) -* [`remove`](#remove) -* [`sample`](#sample) -* [`sampleSize`](#samplesize) -* [`shuffle`](#shuffle) -* [`similarity`](#similarity) -* [`sortedIndex`](#sortedindex) -* [`sortedIndexBy`](#sortedindexby) -* [`sortedLastIndex`](#sortedlastindex) -* [`sortedLastIndexBy`](#sortedlastindexby) -* [`symmetricDifference`](#symmetricdifference) -* [`symmetricDifferenceBy`](#symmetricdifferenceby) -* [`symmetricDifferenceWith`](#symmetricdifferencewith) -* [`tail`](#tail) -* [`take`](#take) -* [`takeRight`](#takeright) -* [`takeRightWhile`](#takerightwhile) -* [`takeWhile`](#takewhile) -* [`union`](#union) -* [`unionBy`](#unionby) -* [`unionWith`](#unionwith) -* [`uniqueElements`](#uniqueelements) -* [`unzip`](#unzip) -* [`unzipWith`](#unzipwith-) -* [`without`](#without) -* [`xProd`](#xprod) -* [`zip`](#zip) -* [`zipObject`](#zipobject) -* [`zipWith`](#zipwith-) - -
- -### 🌐 Browser - -
-View contents - -* [`arrayToHtmlList`](#arraytohtmllist) -* [`bottomVisible`](#bottomvisible) -* [`copyToClipboard`](#copytoclipboard-) -* [`createElement`](#createelement) -* [`createEventHub`](#createeventhub-) -* [`currentURL`](#currenturl) -* [`detectDeviceType`](#detectdevicetype) -* [`elementIsVisibleInViewport`](#elementisvisibleinviewport) -* [`getScrollPosition`](#getscrollposition) -* [`getStyle`](#getstyle) -* [`hasClass`](#hasclass) -* [`hashBrowser`](#hashbrowser-) -* [`hide`](#hide) -* [`httpsRedirect`](#httpsredirect) -* [`observeMutations`](#observemutations-) -* [`off`](#off) -* [`on`](#on) -* [`onUserInputChange`](#onuserinputchange-) -* [`redirect`](#redirect) -* [`runAsync`](#runasync-) -* [`scrollToTop`](#scrolltotop) -* [`setStyle`](#setstyle) -* [`show`](#show) -* [`toggleClass`](#toggleclass) -* [`UUIDGeneratorBrowser`](#uuidgeneratorbrowser) - -
- -### ⏱️ Date - -
-View contents - -* [`formatDuration`](#formatduration) -* [`getColonTimeFromDate`](#getcolontimefromdate) -* [`getDaysDiffBetweenDates`](#getdaysdiffbetweendates) -* [`getMeridiemSuffixOfInteger`](#getmeridiemsuffixofinteger) -* [`tomorrow`](#tomorrow) - -
- -### 🎛️ Function - -
-View contents - -* [`attempt`](#attempt) -* [`bind`](#bind) -* [`bindKey`](#bindkey) -* [`chainAsync`](#chainasync) -* [`compose`](#compose) -* [`composeRight`](#composeright) -* [`converge`](#converge) -* [`curry`](#curry) -* [`debounce`](#debounce) -* [`defer`](#defer) -* [`delay`](#delay) -* [`functionName`](#functionname) -* [`memoize`](#memoize) -* [`negate`](#negate) -* [`once`](#once) -* [`partial`](#partial) -* [`partialRight`](#partialright) -* [`runPromisesInSeries`](#runpromisesinseries) -* [`sleep`](#sleep) -* [`throttle`](#throttle) -* [`times`](#times) -* [`unfold`](#unfold) - -
- -### ➗ Math - -
-View contents - -* [`average`](#average) -* [`averageBy`](#averageby) -* [`clampNumber`](#clampnumber) -* [`digitize`](#digitize) -* [`distance`](#distance) -* [`elo`](#elo-) -* [`factorial`](#factorial) -* [`fibonacci`](#fibonacci) -* [`gcd`](#gcd) -* [`geometricProgression`](#geometricprogression) -* [`hammingDistance`](#hammingdistance) -* [`inRange`](#inrange) -* [`isDivisible`](#isdivisible) -* [`isEven`](#iseven) -* [`isPrime`](#isprime) -* [`lcm`](#lcm) -* [`luhnCheck`](#luhncheck) -* [`maxBy`](#maxby) -* [`median`](#median) -* [`minBy`](#minby) -* [`percentile`](#percentile) -* [`powerset`](#powerset) -* [`primes`](#primes) -* [`randomIntArrayInRange`](#randomintarrayinrange) -* [`randomIntegerInRange`](#randomintegerinrange) -* [`randomNumberInRange`](#randomnumberinrange) -* [`round`](#round) -* [`sdbm`](#sdbm) -* [`standardDeviation`](#standarddeviation) -* [`sum`](#sum) -* [`sumBy`](#sumby) -* [`sumPower`](#sumpower) -* [`toSafeInteger`](#tosafeinteger) - -
- -### 📦 Node - -
-View contents - -* [`atob`](#atob) -* [`btoa`](#btoa) -* [`colorize`](#colorize) -* [`hasFlags`](#hasflags) -* [`hashNode`](#hashnode) -* [`isTravisCI`](#istravisci) -* [`JSONToFile`](#jsontofile) -* [`readFileLines`](#readfilelines) -* [`untildify`](#untildify) -* [`UUIDGeneratorNode`](#uuidgeneratornode) - -
- -### 🗃️ Object - -
-View contents - -* [`bindAll`](#bindall) -* [`deepClone`](#deepclone) -* [`defaults`](#defaults) -* [`equals`](#equals-) -* [`findKey`](#findkey) -* [`findLastKey`](#findlastkey) -* [`flattenObject`](#flattenobject) -* [`forOwn`](#forown) -* [`forOwnRight`](#forownright) -* [`functions`](#functions) -* [`get`](#get) -* [`invertKeyValues`](#invertkeyvalues) -* [`lowercaseKeys`](#lowercasekeys) -* [`mapKeys`](#mapkeys) -* [`mapValues`](#mapvalues) -* [`matches`](#matches) -* [`matchesWith`](#matcheswith) -* [`merge`](#merge) -* [`objectFromPairs`](#objectfrompairs) -* [`objectToPairs`](#objecttopairs) -* [`omit`](#omit) -* [`omitBy`](#omitby) -* [`orderBy`](#orderby) -* [`pick`](#pick) -* [`pickBy`](#pickby) -* [`shallowClone`](#shallowclone) -* [`size`](#size) -* [`transform`](#transform) -* [`truthCheckCollection`](#truthcheckcollection) -* [`unflattenObject`](#unflattenobject-) - -
- -### 📜 String - -
-View contents - -* [`anagrams`](#anagrams) -* [`byteSize`](#bytesize) -* [`capitalize`](#capitalize) -* [`capitalizeEveryWord`](#capitalizeeveryword) -* [`decapitalize`](#decapitalize) -* [`escapeHTML`](#escapehtml) -* [`escapeRegExp`](#escaperegexp) -* [`fromCamelCase`](#fromcamelcase) -* [`isAbsoluteURL`](#isabsoluteurl) -* [`isLowerCase`](#islowercase) -* [`isUpperCase`](#isuppercase) -* [`mask`](#mask) -* [`palindrome`](#palindrome) -* [`pluralize`](#pluralize) -* [`removeNonASCII`](#removenonascii) -* [`reverseString`](#reversestring) -* [`sortCharactersInString`](#sortcharactersinstring) -* [`splitLines`](#splitlines) -* [`stripHTMLTags`](#striphtmltags) -* [`toCamelCase`](#tocamelcase) -* [`toKebabCase`](#tokebabcase) -* [`toSnakeCase`](#tosnakecase) -* [`truncateString`](#truncatestring) -* [`unescapeHTML`](#unescapehtml) -* [`URLJoin`](#urljoin) -* [`words`](#words) - -
- -### 📃 Type - -
-View contents - -* [`getType`](#gettype) -* [`is`](#is) -* [`isArrayLike`](#isarraylike) -* [`isBoolean`](#isboolean) -* [`isEmpty`](#isempty) -* [`isFunction`](#isfunction) -* [`isNil`](#isnil) -* [`isNull`](#isnull) -* [`isNumber`](#isnumber) -* [`isObject`](#isobject) -* [`isObjectLike`](#isobjectlike) -* [`isPlainObject`](#isplainobject) -* [`isPrimitive`](#isprimitive) -* [`isPromiseLike`](#ispromiselike) -* [`isString`](#isstring) -* [`isSymbol`](#issymbol) -* [`isUndefined`](#isundefined) -* [`isValidJSON`](#isvalidjson) - -
- -### 🔧 Utility - -
-View contents - -* [`castArray`](#castarray) -* [`cloneRegExp`](#cloneregexp) -* [`coalesce`](#coalesce) -* [`coalesceFactory`](#coalescefactory) -* [`extendHex`](#extendhex) -* [`getURLParameters`](#geturlparameters) -* [`hexToRGB`](#hextorgb-) -* [`httpGet`](#httpget) -* [`httpPost`](#httppost) -* [`nthArg`](#ntharg) -* [`parseCookie`](#parsecookie) -* [`prettyBytes`](#prettybytes) -* [`randomHexColorCode`](#randomhexcolorcode) -* [`RGBToHex`](#rgbtohex) -* [`serializeCookie`](#serializecookie) -* [`timeTaken`](#timetaken) -* [`toCurrency`](#tocurrency) -* [`toDecimalMark`](#todecimalmark) -* [`toOrdinalSuffix`](#toordinalsuffix) -* [`validateNumber`](#validatenumber) -* [`yesNo`](#yesno) - -
- ---- - ## 🔌 Adapter - -### ary - -Creates a function that accepts up to `n` arguments, ignoring any additional arguments. - -Call the provided function, `fn`, with up to `n` arguments, using `Array.slice(0,n)` and the spread operator (`...`). - -```js -const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); -``` - -
-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) - - +![Logo](/logo.png) + +# 30 seconds of code + +[![License](https://img.shields.io/badge/license-CC0--1.0-blue.svg)](https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE) [![npm Downloads](https://img.shields.io/npm/dt/30-seconds-of-code.svg)](https://www.npmjs.com/package/30-seconds-of-code) [![npm Version](https://img.shields.io/npm/v/30-seconds-of-code.svg)](https://www.npmjs.com/package/30-seconds-of-code) [![Gitter chat](https://img.shields.io/badge/chat-on%20gitter-4FB999.svg)](https://gitter.im/30-seconds-of-code/Lobby) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Travis Build](https://travis-ci.org/Chalarangelo/30-seconds-of-code.svg?branch=master)](https://travis-ci.org/Chalarangelo/30-seconds-of-code) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/207ea6fa2c204ccda61dc3047986e144)](https://www.codacy.com/app/Chalarangelo/30-seconds-of-code?utm_source=github.com&utm_medium=referral&utm_content=Chalarangelo/30-seconds-of-code&utm_campaign=badger) [![Maintainability](https://api.codeclimate.com/v1/badges/e9020d1c963a91c0c8a2/maintainability)](https://codeclimate.com/github/Chalarangelo/30-seconds-of-code/maintainability) [![Insight.io](https://img.shields.io/badge/insight.io-Ready-brightgreen.svg)](https://insight.io/github.com/Chalarangelo/30-seconds-of-code/tree/master/?source=0) [![js-semistandard-style](https://img.shields.io/badge/code%20style-semistandard-brightgreen.svg)](https://github.com/Flet/semistandard) [![ProductHunt](https://img.shields.io/badge/producthunt-vote-orange.svg)](https://www.producthunt.com/posts/30-seconds-of-code) + + +> Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. +test + +- Use Ctrl + F or command + F to search for a snippet. +- Contributions welcome, please read the [contribution guide](CONTRIBUTING.md). +- Snippets are written in ES6, use the [Babel transpiler](https://babeljs.io/) to ensure backwards-compatibility. +- You can import these snippets into your text editor of choice (VSCode, Atom, Sublime) using the files found in [this repo](https://github.com/Rob-Rychs/30-seconds-of-code-texteditorsnippets). +- You can import these snippets into Alfred 3, using [this file](https://github.com/lslvxy/30-seconds-of-code-alfredsnippets). + +#### Package + +⚠️ **WARNING:** Snippets are not production ready. + +You can find a package with all the snippets on [npm](https://www.npmjs.com/package/30-seconds-of-code). + +```bash +# With npm +npm install 30-seconds-of-code + +# With yarn +yarn add 30-seconds-of-code +``` + +CDN links +- [ES2017 Full (UMD)](https://unpkg.com/30-seconds-of-code) +- [ES5 Minified (UMD)](https://unpkg.com/30-seconds-of-code/dist/_30s.es5.min.js) + +
+Details + +**Browser** + +> IMPORTANT: replace the `src` with the full version link and desired target spec (such as ES5 minified)): + +```html + + +``` + +**Node** + +```js +// CommonJS +const _30s = require('30-seconds-of-code'); +_30s.average(1, 2, 3); + +// ES Modules +import _30s from '30-seconds-of-code'; +_30s.average(1, 2, 3); +``` + +To import snippets directly: + +```js +// CommonJS +const { average } = require('30-seconds-of-code'); +average(1, 2, 3); + +// ES Modules +import { average } from '30-seconds-of-code'; +average(1, 2, 3); +``` +
+ +## Table of Contents + +### 🔌 Adapter + +
+View contents + +* [`ary`](#ary) +* [`call`](#call) +* [`collectInto`](#collectinto) +* [`flip`](#flip) +* [`over`](#over) +* [`overArgs`](#overargs) +* [`pipeAsyncFunctions`](#pipeasyncfunctions) +* [`pipeFunctions`](#pipefunctions) +* [`promisify`](#promisify) +* [`rearg`](#rearg) +* [`spreadOver`](#spreadover) +* [`unary`](#unary) + +
+ +### 📚 Array + +
+View contents + +* [`chunk`](#chunk) +* [`compact`](#compact) +* [`countBy`](#countby) +* [`countOccurrences`](#countoccurrences) +* [`deepFlatten`](#deepflatten) +* [`difference`](#difference) +* [`differenceBy`](#differenceby) +* [`differenceWith`](#differencewith) +* [`drop`](#drop) +* [`dropRight`](#dropright) +* [`dropRightWhile`](#droprightwhile) +* [`dropWhile`](#dropwhile) +* [`everyNth`](#everynth) +* [`filterNonUnique`](#filternonunique) +* [`findLast`](#findlast) +* [`findLastIndex`](#findlastindex) +* [`flatten`](#flatten) +* [`forEachRight`](#foreachright) +* [`groupBy`](#groupby) +* [`head`](#head) +* [`indexOfAll`](#indexofall) +* [`initial`](#initial) +* [`initialize2DArray`](#initialize2darray) +* [`initializeArrayWithRange`](#initializearraywithrange) +* [`initializeArrayWithRangeRight`](#initializearraywithrangeright) +* [`initializeArrayWithValues`](#initializearraywithvalues) +* [`intersection`](#intersection) +* [`intersectionBy`](#intersectionby) +* [`intersectionWith`](#intersectionwith) +* [`isSorted`](#issorted) +* [`join`](#join) +* [`last`](#last) +* [`longestItem`](#longestitem) +* [`mapObject`](#mapobject-) +* [`maxN`](#maxn) +* [`minN`](#minn) +* [`nthElement`](#nthelement) +* [`partition`](#partition) +* [`pull`](#pull) +* [`pullAtIndex`](#pullatindex) +* [`pullAtValue`](#pullatvalue) +* [`pullBy`](#pullby-) +* [`reducedFilter`](#reducedfilter) +* [`reduceSuccessive`](#reducesuccessive) +* [`reduceWhich`](#reducewhich) +* [`remove`](#remove) +* [`sample`](#sample) +* [`sampleSize`](#samplesize) +* [`shuffle`](#shuffle) +* [`similarity`](#similarity) +* [`sortedIndex`](#sortedindex) +* [`sortedIndexBy`](#sortedindexby) +* [`sortedLastIndex`](#sortedlastindex) +* [`sortedLastIndexBy`](#sortedlastindexby) +* [`symmetricDifference`](#symmetricdifference) +* [`symmetricDifferenceBy`](#symmetricdifferenceby) +* [`symmetricDifferenceWith`](#symmetricdifferencewith) +* [`tail`](#tail) +* [`take`](#take) +* [`takeRight`](#takeright) +* [`takeRightWhile`](#takerightwhile) +* [`takeWhile`](#takewhile) +* [`union`](#union) +* [`unionBy`](#unionby) +* [`unionWith`](#unionwith) +* [`uniqueElements`](#uniqueelements) +* [`unzip`](#unzip) +* [`unzipWith`](#unzipwith-) +* [`without`](#without) +* [`xProd`](#xprod) +* [`zip`](#zip) +* [`zipObject`](#zipobject) +* [`zipWith`](#zipwith-) + +
+ +### 🌐 Browser + +
+View contents + +* [`arrayToHtmlList`](#arraytohtmllist) +* [`bottomVisible`](#bottomvisible) +* [`copyToClipboard`](#copytoclipboard-) +* [`createElement`](#createelement) +* [`createEventHub`](#createeventhub-) +* [`currentURL`](#currenturl) +* [`detectDeviceType`](#detectdevicetype) +* [`elementIsVisibleInViewport`](#elementisvisibleinviewport) +* [`getScrollPosition`](#getscrollposition) +* [`getStyle`](#getstyle) +* [`hasClass`](#hasclass) +* [`hashBrowser`](#hashbrowser-) +* [`hide`](#hide) +* [`httpsRedirect`](#httpsredirect) +* [`observeMutations`](#observemutations-) +* [`off`](#off) +* [`on`](#on) +* [`onUserInputChange`](#onuserinputchange-) +* [`redirect`](#redirect) +* [`runAsync`](#runasync-) +* [`scrollToTop`](#scrolltotop) +* [`setStyle`](#setstyle) +* [`show`](#show) +* [`toggleClass`](#toggleclass) +* [`UUIDGeneratorBrowser`](#uuidgeneratorbrowser) + +
+ +### ⏱️ Date + +
+View contents + +* [`formatDuration`](#formatduration) +* [`getColonTimeFromDate`](#getcolontimefromdate) +* [`getDaysDiffBetweenDates`](#getdaysdiffbetweendates) +* [`getMeridiemSuffixOfInteger`](#getmeridiemsuffixofinteger) +* [`tomorrow`](#tomorrow) + +
+ +### 🎛️ Function + +
+View contents + +* [`attempt`](#attempt) +* [`bind`](#bind) +* [`bindKey`](#bindkey) +* [`chainAsync`](#chainasync) +* [`compose`](#compose) +* [`composeRight`](#composeright) +* [`converge`](#converge) +* [`curry`](#curry) +* [`debounce`](#debounce) +* [`defer`](#defer) +* [`delay`](#delay) +* [`functionName`](#functionname) +* [`memoize`](#memoize) +* [`negate`](#negate) +* [`once`](#once) +* [`partial`](#partial) +* [`partialRight`](#partialright) +* [`runPromisesInSeries`](#runpromisesinseries) +* [`sleep`](#sleep) +* [`throttle`](#throttle) +* [`times`](#times) +* [`unfold`](#unfold) + +
+ +### ➗ Math + +
+View contents + +* [`average`](#average) +* [`averageBy`](#averageby) +* [`clampNumber`](#clampnumber) +* [`digitize`](#digitize) +* [`distance`](#distance) +* [`elo`](#elo-) +* [`factorial`](#factorial) +* [`fibonacci`](#fibonacci) +* [`gcd`](#gcd) +* [`geometricProgression`](#geometricprogression) +* [`hammingDistance`](#hammingdistance) +* [`inRange`](#inrange) +* [`isDivisible`](#isdivisible) +* [`isEven`](#iseven) +* [`isPrime`](#isprime) +* [`lcm`](#lcm) +* [`luhnCheck`](#luhncheck) +* [`maxBy`](#maxby) +* [`median`](#median) +* [`minBy`](#minby) +* [`percentile`](#percentile) +* [`powerset`](#powerset) +* [`primes`](#primes) +* [`randomIntArrayInRange`](#randomintarrayinrange) +* [`randomIntegerInRange`](#randomintegerinrange) +* [`randomNumberInRange`](#randomnumberinrange) +* [`round`](#round) +* [`sdbm`](#sdbm) +* [`standardDeviation`](#standarddeviation) +* [`sum`](#sum) +* [`sumBy`](#sumby) +* [`sumPower`](#sumpower) +* [`toSafeInteger`](#tosafeinteger) + +
+ +### 📦 Node + +
+View contents + +* [`atob`](#atob) +* [`btoa`](#btoa) +* [`colorize`](#colorize) +* [`hasFlags`](#hasflags) +* [`hashNode`](#hashnode) +* [`isTravisCI`](#istravisci) +* [`JSONToFile`](#jsontofile) +* [`readFileLines`](#readfilelines) +* [`untildify`](#untildify) +* [`UUIDGeneratorNode`](#uuidgeneratornode) + +
+ +### 🗃️ Object + +
+View contents + +* [`bindAll`](#bindall) +* [`deepClone`](#deepclone) +* [`defaults`](#defaults) +* [`equals`](#equals-) +* [`findKey`](#findkey) +* [`findLastKey`](#findlastkey) +* [`flattenObject`](#flattenobject) +* [`forOwn`](#forown) +* [`forOwnRight`](#forownright) +* [`functions`](#functions) +* [`get`](#get) +* [`invertKeyValues`](#invertkeyvalues) +* [`lowercaseKeys`](#lowercasekeys) +* [`mapKeys`](#mapkeys) +* [`mapValues`](#mapvalues) +* [`matches`](#matches) +* [`matchesWith`](#matcheswith) +* [`merge`](#merge) +* [`objectFromPairs`](#objectfrompairs) +* [`objectToPairs`](#objecttopairs) +* [`omit`](#omit) +* [`omitBy`](#omitby) +* [`orderBy`](#orderby) +* [`pick`](#pick) +* [`pickBy`](#pickby) +* [`shallowClone`](#shallowclone) +* [`size`](#size) +* [`transform`](#transform) +* [`truthCheckCollection`](#truthcheckcollection) +* [`unflattenObject`](#unflattenobject-) + +
+ +### 📜 String + +
+View contents + +* [`anagrams`](#anagrams) +* [`byteSize`](#bytesize) +* [`capitalize`](#capitalize) +* [`capitalizeEveryWord`](#capitalizeeveryword) +* [`decapitalize`](#decapitalize) +* [`escapeHTML`](#escapehtml) +* [`escapeRegExp`](#escaperegexp) +* [`fromCamelCase`](#fromcamelcase) +* [`isAbsoluteURL`](#isabsoluteurl) +* [`isLowerCase`](#islowercase) +* [`isUpperCase`](#isuppercase) +* [`mask`](#mask) +* [`palindrome`](#palindrome) +* [`pluralize`](#pluralize) +* [`removeNonASCII`](#removenonascii) +* [`reverseString`](#reversestring) +* [`sortCharactersInString`](#sortcharactersinstring) +* [`splitLines`](#splitlines) +* [`stripHTMLTags`](#striphtmltags) +* [`toCamelCase`](#tocamelcase) +* [`toKebabCase`](#tokebabcase) +* [`toSnakeCase`](#tosnakecase) +* [`truncateString`](#truncatestring) +* [`unescapeHTML`](#unescapehtml) +* [`URLJoin`](#urljoin) +* [`words`](#words) + +
+ +### 📃 Type + +
+View contents + +* [`getType`](#gettype) +* [`is`](#is) +* [`isArrayLike`](#isarraylike) +* [`isBoolean`](#isboolean) +* [`isEmpty`](#isempty) +* [`isFunction`](#isfunction) +* [`isNil`](#isnil) +* [`isNull`](#isnull) +* [`isNumber`](#isnumber) +* [`isObject`](#isobject) +* [`isObjectLike`](#isobjectlike) +* [`isPlainObject`](#isplainobject) +* [`isPrimitive`](#isprimitive) +* [`isPromiseLike`](#ispromiselike) +* [`isString`](#isstring) +* [`isSymbol`](#issymbol) +* [`isUndefined`](#isundefined) +* [`isValidJSON`](#isvalidjson) + +
+ +### 🔧 Utility + +
+View contents + +* [`castArray`](#castarray) +* [`cloneRegExp`](#cloneregexp) +* [`coalesce`](#coalesce) +* [`coalesceFactory`](#coalescefactory) +* [`extendHex`](#extendhex) +* [`getURLParameters`](#geturlparameters) +* [`hexToRGB`](#hextorgb-) +* [`httpGet`](#httpget) +* [`httpPost`](#httppost) +* [`nthArg`](#ntharg) +* [`parseCookie`](#parsecookie) +* [`prettyBytes`](#prettybytes) +* [`randomHexColorCode`](#randomhexcolorcode) +* [`RGBToHex`](#rgbtohex) +* [`serializeCookie`](#serializecookie) +* [`timeTaken`](#timetaken) +* [`toCurrency`](#tocurrency) +* [`toDecimalMark`](#todecimalmark) +* [`toOrdinalSuffix`](#toordinalsuffix) +* [`validateNumber`](#validatenumber) +* [`yesNo`](#yesno) + +
+ +--- + ## 🔌 Adapter + +### ary + +Creates a function that accepts up to `n` arguments, ignoring any additional arguments. + +Call the provided function, `fn`, with up to `n` arguments, using `Array.slice(0,n)` and the spread operator (`...`). + +```js +const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); +``` + +
+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) + + ### call Given a key and a set of arguments, call them when given a context. Primarily useful in composition. Use a closure to call a stored key with stored arguments. -```js -const call = (key, ...args) => context => context[key](...args); +```js +const call = (key, ...args) => context => context[key](...args); ``` -
-Examples - -```js -Promise.resolve([1, 2, 3]) - .then(call('map', x => 2 * x)) - .then(console.log); //[ 2, 4, 6 ] -const map = call.bind(null, 'map'); -Promise.resolve([1, 2, 3]) - .then(map(x => 2 * x)) - .then(console.log); //[ 2, 4, 6 ] +
+Examples + +```js +Promise.resolve([1, 2, 3]) + .then(call('map', x => 2 * x)) + .then(console.log); //[ 2, 4, 6 ] +const map = call.bind(null, 'map'); +Promise.resolve([1, 2, 3]) + .then(map(x => 2 * x)) + .then(console.log); //[ 2, 4, 6 ] ``` - -
- -
[⬆ Back to top](#table-of-contents) - - + +
+ +
[⬆ Back to top](#table-of-contents) + + ### collectInto Changes a function that accepts an array into a variadic function. Given a function, return a closure that collects all inputs into an array-accepting function. -```js -const collectInto = fn => (...args) => fn(args); +```js +const collectInto = fn => (...args) => fn(args); ``` -
-Examples - -```js -const Pall = collectInto(Promise.all.bind(Promise)); -let p1 = Promise.resolve(1); -let p2 = Promise.resolve(2); -let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3)); -Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds) +
+Examples + +```js +const Pall = collectInto(Promise.all.bind(Promise)); +let p1 = Promise.resolve(1); +let p2 = Promise.resolve(2); +let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3)); +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 Flip takes a function as an argument, then makes the first argument the last. Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest. -```js -const flip = fn => (first, ...rest) => fn(...rest, first); +```js +const flip = fn => (first, ...rest) => fn(...rest, first); ``` -
-Examples - -```js -let a = { name: 'John Smith' }; -let b = {}; -const mergeFrom = flip(Object.assign); -let mergePerson = mergeFrom.bind(null, a); -mergePerson(b); // == b -b = {}; -Object.assign(b, a); // == b +
+Examples + +```js +let a = { name: 'John Smith' }; +let b = {}; +const mergeFrom = flip(Object.assign); +let mergePerson = mergeFrom.bind(null, a); +mergePerson(b); // == b +b = {}; +Object.assign(b, a); // == b ``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### over - -Creates a function that invokes each provided function with the arguments it receives and returns the results. - -Use `Array.map()` and `Function.apply()` to apply each function to the given arguments. - -```js -const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); -``` - -
-Examples - -```js -const minMax = over(Math.min, Math.max); -minMax(1, 2, 3, 4, 5); // [1,5] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### overArgs - -Creates a function that invokes the provided function with its arguments transformed. - -Use `Array.map()` to apply `transforms` to `args` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`. - -```js -const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val))); -``` - -
-Examples - -```js -const square = n => n * n; -const double = n => n * 2; -const fn = overArgs((x, y) => [x, y], [square, double]); -fn(9, 3); // [81, 6] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### pipeAsyncFunctions - -Performs left-to-right function composition for asynchronous functions. - -Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition using `Promise.then()`. -The functions can return a combination of: simple values, `Promise`'s, or they can be defined as `async` ones returning through `await`. -All functions must be unary. - -```js -const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); -``` - -
-Examples - -```js -const sum = pipeAsyncFunctions( - x => x + 1, - x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)), - x => x + 3, - async x => (await x) + 4 -); -(async () => { - console.log(await sum(5)); // 15 (after one second) -})(); -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### pipeFunctions - -Performs left-to-right function composition. - -Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition. -The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. - -```js -const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); -``` - -
-Examples - -```js -const add5 = x => x + 5; -const multiply = (x, y) => x * y; -const multiplyAndAdd5 = pipeFunctions(multiply, add5); -multiplyAndAdd5(5, 2); // 15 -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### promisify - -Converts an asynchronous function to return a promise. - -Use currying to return a function returning a `Promise` that calls the original function. -Use the `...rest` operator to pass in all the parameters. - -*In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)* - -```js -const promisify = func => (...args) => - new Promise((resolve, reject) => - func(...args, (err, result) => (err ? reject(err) : resolve(result))) - ); -``` - -
-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) - - -### rearg - -Creates a function that invokes the provided function with its arguments arranged according to the specified indexes. - -Use `Array.reduce()` and `Array.indexOf()` to reorder arguments based on `indexes` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`. - -```js -const rearg = (fn, indexes) => (...args) => - fn( - ...args.reduce( - (acc, val, i) => ((acc[indexes.indexOf(i)] = val), acc), - Array.from({ length: indexes.length }) - ) - ); -``` - -
-Examples - -```js -var rearged = rearg( - function(a, b, c) { - return [a, b, c]; - }, - [2, 0, 1] -); -rearged('b', 'c', 'a'); // ['a', 'b', 'c'] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - + +
+ +
[⬆ Back to top](#table-of-contents) + + +### over + +Creates a function that invokes each provided function with the arguments it receives and returns the results. + +Use `Array.map()` and `Function.apply()` to apply each function to the given arguments. + +```js +const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); +``` + +
+Examples + +```js +const minMax = over(Math.min, Math.max); +minMax(1, 2, 3, 4, 5); // [1,5] +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + +### overArgs + +Creates a function that invokes the provided function with its arguments transformed. + +Use `Array.map()` to apply `transforms` to `args` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`. + +```js +const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val))); +``` + +
+Examples + +```js +const square = n => n * n; +const double = n => n * 2; +const fn = overArgs((x, y) => [x, y], [square, double]); +fn(9, 3); // [81, 6] +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + +### pipeAsyncFunctions + +Performs left-to-right function composition for asynchronous functions. + +Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition using `Promise.then()`. +The functions can return a combination of: simple values, `Promise`'s, or they can be defined as `async` ones returning through `await`. +All functions must be unary. + +```js +const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); +``` + +
+Examples + +```js +const sum = pipeAsyncFunctions( + x => x + 1, + x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)), + x => x + 3, + async x => (await x) + 4 +); +(async () => { + console.log(await sum(5)); // 15 (after one second) +})(); +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + +### pipeFunctions + +Performs left-to-right function composition. + +Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition. +The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. + +```js +const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); +``` + +
+Examples + +```js +const add5 = x => x + 5; +const multiply = (x, y) => x * y; +const multiplyAndAdd5 = pipeFunctions(multiply, add5); +multiplyAndAdd5(5, 2); // 15 +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + +### promisify + +Converts an asynchronous function to return a promise. + +Use currying to return a function returning a `Promise` that calls the original function. +Use the `...rest` operator to pass in all the parameters. + +*In Node 8+, you can use [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original)* + +```js +const promisify = func => (...args) => + new Promise((resolve, reject) => + func(...args, (err, result) => (err ? reject(err) : resolve(result))) + ); +``` + +
+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) + + +### rearg + +Creates a function that invokes the provided function with its arguments arranged according to the specified indexes. + +Use `Array.reduce()` and `Array.indexOf()` to reorder arguments based on `indexes` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`. + +```js +const rearg = (fn, indexes) => (...args) => + fn( + ...args.reduce( + (acc, val, i) => ((acc[indexes.indexOf(i)] = val), acc), + Array.from({ length: indexes.length }) + ) + ); +``` + +
+Examples + +```js +var rearged = rearg( + function(a, b, c) { + return [a, b, c]; + }, + [2, 0, 1] +); +rearged('b', 'c', 'a'); // ['a', 'b', 'c'] +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### spreadOver Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function. Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function. -```js -const spreadOver = fn => argsArr => fn(...argsArr); +```js +const spreadOver = fn => argsArr => fn(...argsArr); ``` -
-Examples - -```js -const arrayMax = spreadOver(Math.max); -arrayMax([1, 2, 3]); // 3 +
+Examples + +```js +const arrayMax = spreadOver(Math.max); +arrayMax([1, 2, 3]); // 3 ``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### unary - -Creates a function that accepts up to one argument, ignoring any additional arguments. - -Call the provided function, `fn`, with just the first argument given. - -```js -const unary = fn => val => fn(val); -``` - -
-Examples - -```js -['6', '8', '10'].map(unary(parseInt)); // [6, 8, 10] -``` - -
- -
[⬆ Back to top](#table-of-contents) - ---- - ## 📚 Array - -### chunk - -Chunks an array into smaller arrays of a specified size. - -Use `Array.from()` to create a new array, that fits the number of chunks that will be produced. -Use `Array.slice()` to map each element of the new array to a chunk the length of `size`. -If the original array can't be split evenly, the final chunk will contain the remaining elements. - -```js -const chunk = (arr, size) => - Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => - arr.slice(i * size, i * size + size) - ); -``` - -
-Examples - -```js -chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### compact - -Removes falsey values from an array. - -Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`). - -```js -const compact = arr => arr.filter(Boolean); -``` - -
-Examples - -```js -compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### countBy - -Groups the elements of an array based on the given function and returns the count of elements in each group. - -Use `Array.map()` to map the values of an array to a function or property name. -Use `Array.reduce()` to create an object, where the keys are produced from the mapped results. - -```js -const countBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { - acc[val] = (acc[val] || 0) + 1; - return acc; - }, {}); -``` - -
-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) - - -### countOccurrences - -Counts the occurrences of a value in an array. - -Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array. - -```js -const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a + 0), 0); -``` - -
-Examples - -```js -countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3 -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### deepFlatten - -Deep flattens an array. - -Use recursion. -Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array. -Recursively flatten each element that is an array. - -```js -const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); -``` - -
-Examples - -```js -deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### difference - -Returns the difference between two arrays. - -Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`. - -```js -const difference = (a, b) => { - const s = new Set(b); - return a.filter(x => !s.has(x)); -}; -``` - -
-Examples - -```js -difference([1, 2, 3], [1, 2, 4]); // [3] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### differenceBy - -Returns the difference between two arrays, after applying the provided function to each array element of both. - -Create a `Set` by applying `fn` to each element in `b`, then use `Array.filter()` in combination with `fn` on `a` to only keep values not contained in the previously created set. - -```js -const differenceBy = (a, b, fn) => { - const s = new Set(b.map(v => fn(v))); - return a.filter(x => !s.has(fn(x))); -}; -``` - -
-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) - - -### differenceWith - -Filters out all values from an array for which the comparator function does not return `true`. - -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 -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) - - -### drop - -Returns a new array with `n` elements removed from the left. - -Use `Array.slice()` to slice the remove the specified number of elements from the left. - -```js -const drop = (arr, n = 1) => arr.slice(n); -``` - -
-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) - - -### dropRight - -Returns a new array with `n` elements removed from the right. - -Use `Array.slice()` to slice the remove the specified number of elements from the right. - -```js -const dropRight = (arr, n = 1) => arr.slice(0, -n); -``` - -
-Examples - -```js -dropRight([1, 2, 3]); // [1,2] -dropRight([1, 2, 3], 2); // [1] -dropRight([1, 2, 3], 42); // [] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### dropRightWhile - -Removes elements from the end of an array until the passed function returns `true`. Returns the remaining elements in the array. - -Loop through the array, using `Array.slice()` to drop the last element of the array until the returned value from the function is `true`. -Returns the remaining elements. - -```js -const dropRightWhile = (arr, func) => { - while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1); - return arr; -}; -``` - -
-Examples - -```js -dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### dropWhile - -Removes elements in an array until the passed function returns `true`. Returns the remaining elements in the array. - -Loop through the array, using `Array.slice()` to drop the first element of the array until the returned value from the function is `true`. -Returns the remaining elements. - -```js -const dropWhile = (arr, func) => { - while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); - return arr; -}; -``` - -
-Examples - -```js -dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### everyNth - -Returns every nth element in an array. - -Use `Array.filter()` to create a new array that contains every nth element of a given array. - -```js -const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); -``` - -
-Examples - -```js -everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### filterNonUnique - -Filters out the non-unique values in an array. - -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 -filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### findLast - -Returns the last element for which the provided function returns a truthy value. - -Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.slice(-1)` to get the last one. - -```js -const findLast = (arr, fn) => arr.filter(fn).slice(-1)[0]; -``` - -
-Examples - -```js -findLast([1, 2, 3, 4], n => n % 2 === 1); // 3 -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### findLastIndex - -Returns the index of the last element for which the provided function returns a truthy value. - -Use `Array.map()` to map each element to an array with its index and value. -Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.slice(-1)` to get the last one. - -```js -const findLastIndex = (arr, fn) => - arr - .map((val, i) => [i, val]) - .filter(val => fn(val[1], val[0], arr)) - .slice(-1)[0][0]; -``` - -
-Examples - -```js -findLastIndex([1, 2, 3, 4], n => n % 2 === 1); // 2 (index of the value 3) -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### flatten - -Flattens an array up to the specified depth. - -Use recursion, decrementing `depth` by 1 for each level of depth. -Use `Array.reduce()` and `Array.concat()` to merge elements or arrays. -Base case, for `depth` equal to `1` stops recursion. -Omit the second argument, `depth` to flatten only to a depth of `1` (single flatten). - -```js -const flatten = (arr, depth = 1) => - depth !== 1 - ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), []) - : arr.reduce((a, v) => a.concat(v), []); -``` - -
-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) - - -### forEachRight - -Executes a provided function once for each array element, starting from the array's last element. - -Use `Array.slice(0)` to clone the given array, `Array.reverse()` to reverse it and `Array.forEach()` to iterate over the reversed array. - -```js -const forEachRight = (arr, callback) => - arr - .slice(0) - .reverse() - .forEach(callback); -``` - -
-Examples - -```js -forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1' -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### groupBy - -Groups the elements of an array based on the given function. - -Use `Array.map()` to map the values of an array to a function or property name. -Use `Array.reduce()` to create an object, where the keys are produced from the mapped results. - -```js -const groupBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { - acc[val] = (acc[val] || []).concat(arr[i]); - return acc; - }, {}); -``` - -
-Examples - -```js -groupBy([6.1, 4.2, 6.3], Math.floor); // {4: [4.2], 6: [6.1, 6.3]} -groupBy(['one', 'two', 'three'], 'length'); // {3: ['one', 'two'], 5: ['three']} -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### head - -Returns the head of a list. - -Use `arr[0]` to return the first element of the passed array. - -```js -const head = arr => arr[0]; -``` - -
-Examples - -```js -head([1, 2, 3]); // 1 -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### indexOfAll - -Returns all indices of `val` in an array. If `val` never occurs, returns `[]`. - -Use `Array.forEach()` to loop over elements and `Array.push()` to store indices for matching elements. -Return the array of indices. - -```js -const indexOfAll = (arr, val) => { - const indices = []; - arr.forEach((el, i) => el === val && indices.push(i)); - return indices; -}; -``` - -
-Examples - -```js -indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3] -indexOfAll([1, 2, 3], 4); // [] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### initial - -Returns all the elements of an array except the last one. - -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 -initial([1, 2, 3]); // [1,2] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### initialize2DArray - -Initializes a 2D array of given width and height and value. - -Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`. - -```js -const initialize2DArray = (w, h, val = null) => - Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val)); -``` - -
-Examples - -```js -initialize2DArray(2, 2, 0); // [[0,0], [0,0]] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### initializeArrayWithRange - -Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`. - -Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range. -You can omit `start` to use a default value of `0`. -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 + 1 - start) / step) }).map((v, i) => i * step + start); -``` - -
-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) - - -### initializeArrayWithRangeRight - -Initializes an array containing the numbers in the specified range (in reverse) where `start` and `end` are inclusive with their common difference `step`. - -Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range. -You can omit `start` to use a default value of `0`. -You can omit `step` to use a default value of `1`. - -```js -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 -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) - - -### initializeArrayWithValues - -Initializes and fills an array with the specified values. - -Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values. -You can omit `val` to use a default value of `0`. - -```js -const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); -``` - -
-Examples - -```js -initializeArrayWithValues(5, 2); // [2,2,2,2,2] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### intersection - -Returns a list of elements that exist in both arrays. - -Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`. - -```js -const intersection = (a, b) => { - const s = new Set(b); - return a.filter(x => s.has(x)); -}; -``` - -
-Examples - -```js -intersection([1, 2, 3], [4, 3, 2]); // [2,3] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### intersectionBy - -Returns a list of elements that exist in both arrays, after applying the provided function to each array element of both. - -Create a `Set` by applying `fn` to all elements in `b`, then use `Array.filter()` on `a` to only keep elements, which produce values contained in `b` when `fn` is applied to them. - -```js -const intersectionBy = (a, b, fn) => { - const s = new Set(b.map(x => fn(x))); - return a.filter(x => s.has(fn(x))); -}; -``` - -
-Examples - -```js -intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### intersectionWith - -Returns a list of elements that exist in both arrays, using a provided comparator function. - -Use `Array.filter()` and `Array.findIndex()` in combination with the provided comparator to determine intersecting values. - -```js -const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1); -``` - -
-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) - - -### isSorted - -Returns `1` if the array is sorted in ascending order, `-1` if it is sorted in descending order or `0` if it is not sorted. - -Calculate the ordering `direction` for the first two elements. -Use `Object.entries()` to loop over array objects and compare them in pairs. -Return `0` if the `direction` changes or the `direction` if the last element is reached. - -```js -const isSorted = arr => { - const direction = arr[0] > arr[1] ? -1 : 1; - for (let [i, val] of arr.entries()) - if (i === arr.length - 1) return direction; - else if ((val - arr[i + 1]) * direction > 0) return 0; -}; -``` - -
-Examples - -```js -isSorted([0, 1, 2, 2]); // 1 -isSorted([4, 3, 2]); // -1 -isSorted([4, 3, 5]); // 0 -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### join - -Joins all elements of an array into a string and returns this string. Uses a separator and an end separator. - -Use `Array.reduce()` to combine elements into a string. -Omit the second argument, `separator`, to use a default separator of `','`. -Omit the third argument, `end`, to use the same value as `separator` by default. - -```js -const join = (arr, separator = ',', end = separator) => - arr.reduce( - (acc, val, i) => - i === arr.length - 2 - ? acc + val + end - : i === arr.length - 1 ? acc + val : acc + val + separator, - '' - ); -``` - -
-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) - - -### last - -Returns the last element in an array. - -Use `arr.length - 1` to compute the index of the last element of the given array and returning it. - -```js -const last = arr => arr[arr.length - 1]; -``` - -
-Examples - -```js -last([1, 2, 3]); // 3 -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### longestItem - -Takes any number of iterable objects or objects with a `length` property and returns the longest one. - -Use `Array.sort()` to sort all arguments by `length`, return the first (longest) one. - -```js -const longestItem = (...vals) => [...vals].sort((a, b) => b.length - a.length)[0]; -``` - -
-Examples - -```js -longestItem('this', 'is', 'a', 'testcase'); // 'testcase' -longestItem(...['a', 'ab', 'abc']); // 'abc' -longestItem(...['a', 'ab', 'abc'], 'abcd'); // 'abcd' -longestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5] -longestItem([1, 2, 3], 'foobar'); // 'foobar' -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### mapObject ![advanced](/advanced.svg) - -Maps the values of an array to an object using a function, where the key-value pairs consist of the original value as the key and the mapped value. - -Use an anonymous inner function scope to declare an undefined memory space, using closures to store a return value. Use a new `Array` to store the array with a map of the function over its data set and a comma operator to return a second step, without needing to move from one context to another (due to closures and order of operations). - -```js -const mapObject = (arr, fn) => - (a => ( - (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) - ))(); -``` - -
-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) - - -### maxN - -Returns the `n` maximum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in descending order). - -Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order. -Use `Array.slice()` to get the specified number of elements. -Omit the second argument, `n`, to get a one-element array. - -```js -const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); -``` - -
-Examples - -```js -maxN([1, 2, 3]); // [3] -maxN([1, 2, 3], 2); // [3,2] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### minN - -Returns the `n` minimum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in ascending order). - -Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in ascending order. -Use `Array.slice()` to get the specified number of elements. -Omit the second argument, `n`, to get a one-element array. - -```js -const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); -``` -
-Examples - -```js -minN([1, 2, 3]); // [1] -minN([1, 2, 3], 2); // [1,2] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### nthElement - -Returns the nth element of an array. - -Use `Array.slice()` to get an array containing the nth element at the first place. -If the index is out of bounds, return `[]`. -Omit the second argument, `n`, to get the first element of the array. - -```js -const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0]; -``` - -
-Examples - -```js -nthElement(['a', 'b', 'c'], 1); // 'b' -nthElement(['a', 'b', 'b'], -3); // 'a' -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### partition - -Groups the elements into two arrays, depending on the provided function's truthiness for each element. - -Use `Array.reduce()` to create an array of two arrays. -Use `Array.push()` to add elements for which `fn` returns `true` to the first array and elements for which `fn` returns `false` to the second one. - -```js -const partition = (arr, fn) => - arr.reduce( - (acc, val, i, arr) => { - acc[fn(val, i, arr) ? 0 : 1].push(val); - return acc; - }, - [[], []] - ); -``` - -
-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) - - -### pull - -Mutates the original array to filter out the values specified. - -Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. -Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. - -_(For a snippet that does not mutate the original array see [`without`](#without))_ - -```js -const pull = (arr, ...args) => { - let argState = Array.isArray(args[0]) ? args[0] : args; - let pulled = arr.filter((v, i) => !argState.includes(v)); - arr.length = 0; - pulled.forEach(v => arr.push(v)); -}; -``` - -
-Examples - -```js -let myArray = ['a', 'b', 'c', 'a', 'b', 'c']; -pull(myArray, 'a', 'c'); // myArray = [ 'b', 'b' ] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### pullAtIndex - -Mutates the original array to filter out the values at the specified indexes. - -Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. -Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. -Use `Array.push()` to keep track of pulled values - -```js -const pullAtIndex = (arr, pullArr) => { - let removed = []; - let pulled = arr - .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v)) - .filter((v, i) => !pullArr.includes(i)); - arr.length = 0; - pulled.forEach(v => arr.push(v)); - return removed; -}; -``` - -
-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) - - -### pullAtValue - -Mutates the original array to filter out the values specified. Returns the removed elements. - -Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. -Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. -Use `Array.push()` to keep track of pulled values - -```js -const pullAtValue = (arr, pullArr) => { - let removed = [], - pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)), - mutateTo = arr.filter((v, i) => !pullArr.includes(v)); - arr.length = 0; - mutateTo.forEach(v => arr.push(v)); - return removed; -}; -``` - -
-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) - - -### pullBy ![advanced](/advanced.svg) - -Mutates the original array to filter out the values specified, based on a given iterator function. - -Check if the last argument provided in a function. -Use `Array.map()` to apply the iterator function `fn` to all array elements. -Use `Array.filter()` and `Array.includes()` to pull out the values that are not needed. -Use `Array.length = 0` to mutate the passed in an array by resetting it's length to zero and `Array.push()` to re-populate it with only the pulled values. - -```js -const pullBy = (arr, ...args) => { - const length = args.length; - let fn = length > 1 ? args[length - 1] : undefined; - fn = typeof fn == 'function' ? (args.pop(), fn) : undefined; - let argState = (Array.isArray(args[0]) ? args[0] : args).map(val => fn(val)); - let pulled = arr.filter((v, i) => !argState.includes(fn(v))); - arr.length = 0; - pulled.forEach(v => arr.push(v)); -}; -``` - -
-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) - - -### reducedFilter - -Filter an array of objects based on a condition while also filtering out unspecified keys. - -Use `Array.filter()` to filter the array based on the predicate `fn` so that it returns the objects for which the condition returned a truthy value. -On the filtered array, use `Array.map()` to return the new object using `Array.reduce()` to filter out the keys which were not supplied as the `keys` argument. - -```js -const reducedFilter = (data, keys, fn) => - data.filter(fn).map(el => - keys.reduce((acc, key) => { - acc[key] = el[key]; - return acc; - }, {}) - ); -``` - -
-Examples - -```js -const data = [ - { - id: 1, - name: 'john', - age: 24 - }, - { - id: 2, - name: 'mike', - age: 50 - } -]; - -reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### reduceSuccessive - -Applies a function against an accumulator and each element in the array (from left to right), returning an array of successively reduced values. - -Use `Array.reduce()` to apply the given function to the given array, storing each new result. - -```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 -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) - - -### reduceWhich - -Returns the minimum/maximum value of an array, after applying the provided function to set comparing rule. - -Use `Array.reduce()` in combination with the `comparator` function to get the appropriate element in the array. -You can omit the second parameter, `comparator`, to use the default one that returns the minimum element in the array. - -```js -const reduceWhich = (arr, comparator = (a, b) => a - b) => - arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a)); -``` - -
-Examples - -```js -reduceWhich([1, 3, 2]); // 1 -reduceWhich([1, 3, 2], (a, b) => b - a); // 3 -reduceWhich( - [{ name: 'Tom', age: 12 }, { name: 'Jack', age: 18 }, { name: 'Lucy', age: 9 }], - (a, b) => a.age - b.age -); // {name: "Lucy", age: 9} -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### remove - -Removes elements from an array for which the given function returns `false`. - -Use `Array.filter()` to find array elements that return truthy values and `Array.reduce()` to remove elements using `Array.splice()`. -The `func` is invoked with three arguments (`value, index, array`). - -```js -const remove = (arr, func) => - Array.isArray(arr) - ? arr.filter(func).reduce((acc, val) => { - arr.splice(arr.indexOf(val), 1); - return acc.concat(val); - }, []) - : []; -``` - -
-Examples - -```js -remove([1, 2, 3, 4], n => n % 2 === 0); // [2, 4] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### sample - -Returns a random element from an array. - -Use `Math.random()` to generate a random number, multiply it by `length` and round it of to the nearest whole number using `Math.floor()`. -This method also works with strings. - -```js -const sample = arr => arr[Math.floor(Math.random() * arr.length)]; -``` - -
-Examples - -```js -sample([3, 7, 9, 11]); // 9 -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### sampleSize - -Gets `n` random elements at unique keys from `array` up to the size of `array`. - -Shuffle the array using the [Fisher-Yates algorithm](https://github.com/chalarangelo/30-seconds-of-code#shuffle). -Use `Array.slice()` to get the first `n` elements. -Omit the second argument, `n` to get only one element at random from the array. - -```js -const sampleSize = ([...arr], n = 1) => { - let m = arr.length; - while (m) { - const i = Math.floor(Math.random() * m--); - [arr[m], arr[i]] = [arr[i], arr[m]]; - } - return arr.slice(0, n); -}; -``` - -
-Examples - -```js -sampleSize([1, 2, 3], 2); // [3,1] -sampleSize([1, 2, 3], 4); // [2,3,1] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### shuffle - -Randomizes the order of the values of an array, returning a new array. - -Uses the [Fisher-Yates algorithm](https://github.com/chalarangelo/30-seconds-of-code#shuffle) to reorder the elements of the array. - -```js -const shuffle = ([...arr]) => { - let m = arr.length; - while (m) { - const i = Math.floor(Math.random() * m--); - [arr[m], arr[i]] = [arr[i], arr[m]]; - } - return arr; -}; -``` - -
-Examples - -```js -const foo = [1, 2, 3]; -shuffle(foo); // [2,3,1], foo = [1,2,3] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### similarity - -Returns an array of elements that appear in both arrays. - -Use `Array.filter()` to remove values that are not part of `values`, determined using `Array.includes()`. - -```js -const similarity = (arr, values) => arr.filter(v => values.includes(v)); -``` - -
-Examples - -```js -similarity([1, 2, 3], [1, 2, 4]); // [1,2] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### sortedIndex - -Returns the lowest index at which value should be inserted into array in order to maintain its sort order. - -Check if the array is sorted in descending order (loosely). -Use `Array.findIndex()` to find the appropriate index where the element should be inserted. - -```js -const sortedIndex = (arr, n) => { - const isDescending = arr[0] > arr[arr.length - 1]; - const index = arr.findIndex(el => (isDescending ? n >= el : n <= el)); - return index === -1 ? arr.length : index; -}; -``` - -
-Examples - -```js -sortedIndex([5, 3, 2, 1], 4); // 1 -sortedIndex([30, 50], 40); // 1 -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### sortedIndexBy - -Returns the lowest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function. - -Check if the array is sorted in descending order (loosely). -Use `Array.findIndex()` to find the appropriate index where the element should be inserted, based on the iterator function `fn`. - -```js -const sortedIndexBy = (arr, n, fn) => { - const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); - const val = fn(n); - const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el))); - return index === -1 ? arr.length : index; -}; -``` - -
-Examples - -```js -sortedIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 0 -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### sortedLastIndex - -Returns the highest index at which value should be inserted into array in order to maintain its sort order. - -Check if the array is sorted in descending order (loosely). -Use `Array.map()` to map each element to an array with its index and value. -Use `Array.reverse()` and `Array.findIndex()` to find the appropriate last index where the element should be inserted. - -```js -const sortedLastIndex = (arr, n) => { - const isDescending = arr[0] > arr[arr.length - 1]; - const index = arr - .map((val, i) => [i, val]) - .reverse() - .findIndex(el => (isDescending ? n <= el[1] : n >= el[1])); - return index === -1 ? 0 : arr.length - index - 1; -}; -``` - -
-Examples - -```js -sortedLastIndex([10, 20, 30, 30, 40], 30); // 3 -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### sortedLastIndexBy - -Returns the highest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function. - -Check if the array is sorted in descending order (loosely). -Use `Array.reverse()` and `Array.findIndex()` to find the appropriate last index where the element should be inserted, based on the iterator function `fn`.. - -```js -const sortedLastIndexBy = (arr, n, fn) => { - const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); - const val = fn(n); - const index = arr - .map((val, i) => [i, fn(val)]) - .reverse() - .findIndex(el => (isDescending ? val <= el[1] : val >= el[1])); - return index === -1 ? 0 : arr.length - index; -}; -``` - -
-Examples - -```js -sortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 1 -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### symmetricDifference - -Returns the symmetric difference between two arrays. - -Create a `Set` from each array, then use `Array.filter()` on each of them to only keep values not contained in the other. - -```js -const symmetricDifference = (a, b) => { - const sA = new Set(a), - sB = new Set(b); - return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; -}; -``` - -
-Examples - -```js -symmetricDifference([1, 2, 3], [1, 2, 4]); // [3,4] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### symmetricDifferenceBy - -Returns the symmetric difference between two arrays, after applying the provided function to each array element of both. - -Create a `Set` by applying `fn` to each array's elements, then use `Array.filter()` on each of them to only keep values not contained in the other. - -```js -const symmetricDifferenceBy = (a, b, fn) => { - const sA = new Set(a.map(v => fn(v))), - 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 -symmetricDifferenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [ 1.2, 3.4 ] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### symmetricDifferenceWith - -Returns the symmetric difference between two arrays, using a provided function as a comparator. - -Use `Array.filter()` and `Array.findIndex()` to find the appropriate values. - -```js -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 -symmetricDifferenceWith( - [1, 1.2, 1.5, 3, 0], - [1.9, 3, 0, 3.9], - (a, b) => Math.round(a) === Math.round(b) -); // [1, 1.2, 3.9] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### tail - -Returns all elements in an array except for the first one. - -Return `Array.slice(1)` if the array's `length` is more than `1`, otherwise, return the whole array. - -```js -const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); -``` - -
-Examples - -```js -tail([1, 2, 3]); // [2,3] -tail([1]); // [1] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### take - -Returns an array with n elements removed from the beginning. - -Use `Array.slice()` to create a slice of the array with `n` elements taken from the beginning. - -```js -const take = (arr, n = 1) => arr.slice(0, n); -``` - -
-Examples - -```js -take([1, 2, 3], 5); // [1, 2, 3] -take([1, 2, 3], 0); // [] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### takeRight - -Returns an array with n elements removed from the end. - -Use `Array.slice()` to create a slice of the array with `n` elements taken from the end. - -```js -const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); -``` - -
-Examples - -```js -takeRight([1, 2, 3], 2); // [ 2, 3 ] -takeRight([1, 2, 3]); // [3] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### takeRightWhile - -Removes elements from the end of an array until the passed function returns `true`. Returns the removed elements. - -Loop through the array, using a `for...of` loop over `Array.keys()` until the returned value from the function is `true`. -Return the removed elements, using `Array.reverse()` and `Array.slice()`. - -```js -const takeRightWhile = (arr, func) => { - for (let i of arr.reverse().keys()) - if (func(arr[i])) return arr.reverse().slice(arr.length - i, arr.length); - return arr; -}; -``` - -
-Examples - -```js -takeRightWhile([1, 2, 3, 4], n => n < 3); // [3, 4] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### takeWhile - -Removes elements in an array until the passed function returns `true`. Returns the removed elements. - -Loop through the array, using a `for...of` loop over `Array.keys()` until the returned value from the function is `true`. -Return the removed elements, using `Array.slice()`. - -```js -const takeWhile = (arr, func) => { - for (let i of arr.keys()) if (func(arr[i])) return arr.slice(0, i); - return arr; -}; -``` - -
-Examples - -```js -takeWhile([1, 2, 3, 4], n => n >= 3); // [1, 2] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### union - -Returns every element that exists in any of the two arrays once. - -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 -union([1, 2, 3], [4, 3, 2]); // [1,2,3,4] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### unionBy - -Returns every element that exists in any of the two arrays once, after applying the provided function to each array element of both. - -Create a `Set` by applying all `fn` to all values of `a`. -Create a `Set` from `a` and all elements in `b` whose value, after applying `fn` does not match a value in the previously created set. -Return the last set converted to an array. - -```js -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 -unionBy([2.1], [1.2, 2.3], Math.floor); // [2.1, 1.2] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### unionWith - -Returns every element that exists in any of the two arrays once, using a provided comparator function. - -Create a `Set` with all values of `a` and values in `b` for which the comparator finds no matches in `a`, using `Array.findIndex()`. - -```js -const unionWith = (a, b, comp) => - Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)])); -``` - -
-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) - - -### uniqueElements - -Returns all unique values of an array. - -Use ES6 `Set` and the `...rest` operator to discard all duplicated values. - -```js -const uniqueElements = arr => [...new Set(arr)]; -``` - -
-Examples - -```js -uniqueElements([1, 2, 2, 3, 4, 4, 5]); // [1,2,3,4,5] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### unzip - -Creates an array of arrays, ungrouping the elements in an array produced by [zip](#zip). - -Use `Math.max.apply()` to get the longest subarray in the array, `Array.map()` to make each element an array. -Use `Array.reduce()` and `Array.forEach()` to map grouped values to individual arrays. - -```js -const unzip = arr => - arr.reduce( - (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), - Array.from({ - length: Math.max(...arr.map(x => x.length)) - }).map(x => []) - ); -``` - -
-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) - - -### unzipWith ![advanced](/advanced.svg) - -Creates an array of elements, ungrouping the elements in an array produced by [zip](#zip) and applying the provided function. - -Use `Math.max.apply()` to get the longest subarray in the array, `Array.map()` to make each element an array. -Use `Array.reduce()` and `Array.forEach()` to map grouped values to individual arrays. -Use `Array.map()` and the spread operator (`...`) to apply `fn` to each individual group of elements. - -```js -const unzipWith = (arr, fn) => - arr - .reduce( - (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), - Array.from({ - length: Math.max(...arr.map(x => x.length)) - }).map(x => []) - ) - .map(val => fn(...val)); -``` - -
-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) - - -### without - -Filters out the elements of an array, that have one of the specified values. - -Use `Array.filter()` to create an array excluding(using `!Array.includes()`) all given values. - -_(For a snippet that mutates the original array see [`pull`](#pull))_ - -```js -const without = (arr, ...args) => arr.filter(v => !args.includes(v)); -``` - -
-Examples - -```js -without([2, 1, 2, 3], 1, 2); // [3] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### xProd - -Creates a new array out of the two supplied by creating each possible pair from the arrays. - -Use `Array.reduce()`, `Array.map()` and `Array.concat()` to produce every possible pair from the elements of the two arrays and save them in an array. - -```js -const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []); -``` - -
-Examples - -```js -xProd([1, 2], ['a', 'b']); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### zip - -Creates an array of elements, grouped based on the position in the original arrays. - -Use `Math.max.apply()` to get the longest array in the arguments. -Creates an array with that length as return value and use `Array.from()` with a map-function to create an array of grouped elements. -If lengths of the argument-arrays vary, `undefined` is used where no value could be found. - -```js -const zip = (...arrays) => { - const maxLength = Math.max(...arrays.map(x => x.length)); - return Array.from({ length: maxLength }).map((_, i) => { - return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]); - }); -}; -``` - -
-Examples - -```js -zip(['a', 'b'], [1, 2], [true, false]); // [['a', 1, true], ['b', 2, false]] -zip(['a'], [1, 2], [true, false]); // [['a', 1, true], [undefined, 2, false]] -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### zipObject - -Given an array of valid property identifiers and an array of values, return an object associating the properties to the values. - -Since an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using `Array.reduce()`. - -```js -const zipObject = (props, values) => - props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {}); -``` - -
-Examples - -```js -zipObject(['a', 'b', 'c'], [1, 2]); // {a: 1, b: 2, c: undefined} -zipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2} -``` - -
- -
[⬆ Back to top](#table-of-contents) - - -### zipWith ![advanced](/advanced.svg) - -Creates an array of elements, grouped based on the position in the original arrays and using function as the last value to specify how grouped values should be combined. - -Check if the last argument provided in a function. -Use `Math.max()` to get the longest array in the arguments. -Creates an array with that length as return value and use `Array.from()` with a map-function to create an array of grouped elements. -If lengths of the argument-arrays vary, `undefined` is used where no value could be found. -The function is invoked with the elements of each group `(...group)`. - -```js -const zipWith = (...arrays) => { - const length = arrays.length; - let fn = length > 1 ? arrays[length - 1] : undefined; - fn = typeof fn == 'function' ? (arrays.pop(), fn) : undefined; - const maxLength = Math.max(...arrays.map(x => x.length)); - const result = Array.from({ length: maxLength }).map((_, i) => { - return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]); - }); - return fn ? result.map(arr => fn(...arr)) : result; -}; -``` - -
-Examples - -```js -zipWith([1, 2], [10, 20], [100, 200], (a, b, c) => a + b + c); // [111,222] -zipWith( - [1, 2, 3], - [10, 20], - [100, 200], - (a, b, c) => (a != null ? a : 'a') + (b != null ? b : 'b') + (c != null ? c : 'c') -); // [111, 222, '3bc'] -``` - -
- -
[⬆ Back to top](#table-of-contents) - ---- - ## 🌐 Browser - -### arrayToHtmlList - -Converts the given array elements into `
  • ` tags and appends them to the list of the given id. - -Use `Array.map()` and `document.querySelector()` to create a list of html tags. - -```js -const arrayToHtmlList = (arr, listID) => - arr.map(item => (document.querySelector('#' + listID).innerHTML += `
  • ${item}
  • `)); -``` - -
    -Examples - -```js -arrayToHtmlList(['item 1', 'item 2'], 'myListID'); -``` - -
    - -
    [⬆ Back to top](#table-of-contents) - - -### bottomVisible - -Returns `true` if the bottom of the page is visible, `false` otherwise. - -Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible. - -```js -const bottomVisible = () => - document.documentElement.clientHeight + window.scrollY >= - (document.documentElement.scrollHeight || document.documentElement.clientHeight); -``` - -
    -Examples - -```js -bottomVisible(); // true -``` - -
    - -
    [⬆ Back to top](#table-of-contents) - - -### copyToClipboard ![advanced](/advanced.svg) - -Copy a string to the clipboard. Only works as a result of user action (i.e. inside a `click` event listener). - -Create a new `