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 (...).
const ary = ( fn, n) => ( ... args) => fn ( ... args. slice ( 0 , n));
+ }
Adapter ary call collectInto flip over overArgs pipeAsyncFunctions pipeFunctions promisify rearg spreadOver unary Array all any bifurcate bifurcateBy chunk compact countBy countOccurrences deepFlatten difference differenceBy differenceWith drop dropRight dropRightWhile dropWhile everyNth filterNonUnique findLast findLastIndex flatten forEachRight groupBy head indexOfAll initial initialize2DArray initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues intersection intersectionBy intersectionWith isSorted join last longestItem mapObject maxN minN none nthElement offset partition permutations pull pullAtIndex pullAtValue pullBy reducedFilter reduceSuccessive reduceWhich remove sample sampleSize shuffle similarity sortedIndex sortedIndexBy sortedLastIndex sortedLastIndexBy stableSort symmetricDifference symmetricDifferenceBy symmetricDifferenceWith tail take takeRight takeRightWhile takeWhile union unionBy unionWith uniqueElements unzip unzipWith without xProd zip zipObject zipWith Browser arrayToHtmlList bottomVisible copyToClipboard createElement createEventHub currentURL detectDeviceType elementIsVisibleInViewport getScrollPosition getStyle hasClass hashBrowser hide httpsRedirect observeMutations off on onUserInputChange prefix recordAnimationFrames redirect runAsync scrollToTop setStyle show smoothScroll toggleClass UUIDGeneratorBrowser Date formatDuration getColonTimeFromDate getDaysDiffBetweenDates getMeridiemSuffixOfInteger tomorrow Function attempt bind bindKey chainAsync compose composeRight converge curry debounce defer delay functionName hz memoize negate once partial partialRight runPromisesInSeries sleep throttle times uncurry unfold Math approximatelyEqual average averageBy binomialCoefficient clampNumber degreesToRads digitize distance elo factorial fibonacci gcd geometricProgression hammingDistance inRange isDivisible isEven isPrime lcm luhnCheck maxBy median minBy percentile powerset primes radsToDegrees randomIntArrayInRange randomIntegerInRange randomNumberInRange round sdbm standardDeviation sum sumBy sumPower toSafeInteger Node atob btoa colorize hasFlags hashNode isTravisCI JSONToFile readFileLines untildify UUIDGeneratorNode Object bindAll deepClone defaults equals findKey findLastKey flattenObject forOwn forOwnRight functions get invertKeyValues lowercaseKeys mapKeys mapValues matches matchesWith merge nest objectFromPairs objectToPairs omit omitBy orderBy pick pickBy renameKeys shallowClone size transform truthCheckCollection unflattenObject String byteSize capitalize capitalizeEveryWord decapitalize escapeHTML escapeRegExp fromCamelCase isAbsoluteURL isAnagram isLowerCase isUpperCase mask pad palindrome pluralize removeNonASCII reverseString sortCharactersInString splitLines stringPermutations stripHTMLTags toCamelCase toKebabCase toSnakeCase truncateString unescapeHTML URLJoin words Type getType is isArrayLike isBoolean isEmpty isFunction isNil isNull isNumber isObject isObjectLike isPlainObject isPrimitive isPromiseLike isString isSymbol isUndefined isValidJSON Utility castArray cloneRegExp coalesce coalesceFactory extendHex getURLParameters hexToRGB httpGet httpPost isBrowser mostPerformant nthArg parseCookie prettyBytes randomHexColorCode RGBToHex serializeCookie timeTaken toCurrency toDecimalMark toOrdinalSuffix validateNumber 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 (...).
const ary = ( fn, n) => ( ... args) => fn ( ... args. slice ( 0 , n));
Show examples const firstTwoMax = ary ( Math. max, 2 );
[[ 2 , 6 , 'a' ], [ 8 , 4 , 6 ], [ 10 ]]. map ( x => firstTwoMax ( ... x));
📋 Copy to clipboard call Given a key and a set of arguments, call them when given a context. Primarily useful in composition.
Use a closure to call a stored key with stored arguments.
const call = ( key, ... args) => context => context[ key]( ... args);
diff --git a/docs/archive.html b/docs/archive.html
index 551c8dfb3..65fd42c0c 100644
--- a/docs/archive.html
+++ b/docs/archive.html
@@ -56,7 +56,7 @@
document.getElementById('doc-drawer-checkbox').checked = false;
}
}, false);
- }Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
View collection
Snippets Archive These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.
binarySearch Use recursion. Similar to Array.indexOf() that finds the index of a value within an array. The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or Array.indexOf().
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half. Repeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return -1.
const binarySearch = ( arr, val, start = 0 , end = arr. length - 1 ) => {
+ }Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
View collection
Snippets Archive These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.
binarySearch Use recursion. Similar to Array.indexOf() that finds the index of a value within an array. The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or Array.indexOf().
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half. Repeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return -1.
const binarySearch = ( arr, val, start = 0 , end = arr. length - 1 ) => {
if ( start > end) return - 1 ;
const mid = Math. floor (( start + end) / 2 );
if ( arr[ mid] > val) return binarySearch ( arr, val, start, mid - 1 );
diff --git a/docs/array.html b/docs/array.html
index aae30e511..80400c469 100644
--- a/docs/array.html
+++ b/docs/array.html
@@ -79,7 +79,7 @@
document.getElementById('doc-drawer-checkbox').checked = false;
}
}, false);
- }
Adapter ary call collectInto flip over overArgs pipeAsyncFunctions pipeFunctions promisify rearg spreadOver unary Array all any bifurcate bifurcateBy chunk compact countBy countOccurrences deepFlatten difference differenceBy differenceWith drop dropRight dropRightWhile dropWhile everyNth filterNonUnique findLast findLastIndex flatten forEachRight groupBy head indexOfAll initial initialize2DArray initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues intersection intersectionBy intersectionWith isSorted join last longestItem mapObject maxN minN none nthElement offset partition permutations pull pullAtIndex pullAtValue pullBy reducedFilter reduceSuccessive reduceWhich remove sample sampleSize shuffle similarity sortedIndex sortedIndexBy sortedLastIndex sortedLastIndexBy stableSort symmetricDifference symmetricDifferenceBy symmetricDifferenceWith tail take takeRight takeRightWhile takeWhile union unionBy unionWith uniqueElements unzip unzipWith without xProd zip zipObject zipWith Browser arrayToHtmlList bottomVisible copyToClipboard createElement createEventHub currentURL detectDeviceType elementIsVisibleInViewport getScrollPosition getStyle hasClass hashBrowser hide httpsRedirect observeMutations off on onUserInputChange prefix recordAnimationFrames redirect runAsync scrollToTop setStyle show smoothScroll toggleClass UUIDGeneratorBrowser Date formatDuration getColonTimeFromDate getDaysDiffBetweenDates getMeridiemSuffixOfInteger tomorrow Function attempt bind bindKey chainAsync compose composeRight converge curry debounce defer delay functionName hz memoize negate once partial partialRight runPromisesInSeries sleep throttle times uncurry unfold Math approximatelyEqual average averageBy binomialCoefficient clampNumber degreesToRads digitize distance elo factorial fibonacci gcd geometricProgression hammingDistance inRange isDivisible isEven isPrime lcm luhnCheck maxBy median minBy percentile powerset primes radsToDegrees randomIntArrayInRange randomIntegerInRange randomNumberInRange round sdbm standardDeviation sum sumBy sumPower toSafeInteger Node atob btoa colorize hasFlags hashNode isTravisCI JSONToFile readFileLines untildify UUIDGeneratorNode Object bindAll deepClone defaults equals findKey findLastKey flattenObject forOwn forOwnRight functions get invertKeyValues lowercaseKeys mapKeys mapValues matches matchesWith merge nest objectFromPairs objectToPairs omit omitBy orderBy pick pickBy renameKeys shallowClone size transform truthCheckCollection unflattenObject String byteSize capitalize capitalizeEveryWord decapitalize escapeHTML escapeRegExp fromCamelCase isAbsoluteURL isAnagram isLowerCase isUpperCase mask pad palindrome pluralize removeNonASCII reverseString sortCharactersInString splitLines stringPermutations stripHTMLTags toCamelCase toKebabCase toSnakeCase truncateString unescapeHTML URLJoin words Type getType is isArrayLike isBoolean isEmpty isFunction isNil isNull isNumber isObject isObjectLike isPlainObject isPrimitive isPromiseLike isString isSymbol isUndefined isValidJSON Utility castArray cloneRegExp coalesce coalesceFactory extendHex getURLParameters hexToRGB httpGet httpPost isBrowser mostPerformant nthArg parseCookie prettyBytes randomHexColorCode RGBToHex serializeCookie timeTaken toCurrency toDecimalMark toOrdinalSuffix validateNumber yesNo Array all Returns true if the provided predicate function returns true for all elements in a collection, false otherwise.
Use Array.every() to test if all elements in the collection return true based on fn. Omit the second argument, fn, to use Boolean as a default.
const all = ( arr, fn = Boolean) => arr. every ( fn);
+ }
Adapter ary call collectInto flip over overArgs pipeAsyncFunctions pipeFunctions promisify rearg spreadOver unary Array all any bifurcate bifurcateBy chunk compact countBy countOccurrences deepFlatten difference differenceBy differenceWith drop dropRight dropRightWhile dropWhile everyNth filterNonUnique findLast findLastIndex flatten forEachRight groupBy head indexOfAll initial initialize2DArray initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues intersection intersectionBy intersectionWith isSorted join last longestItem mapObject maxN minN none nthElement offset partition permutations pull pullAtIndex pullAtValue pullBy reducedFilter reduceSuccessive reduceWhich remove sample sampleSize shuffle similarity sortedIndex sortedIndexBy sortedLastIndex sortedLastIndexBy stableSort symmetricDifference symmetricDifferenceBy symmetricDifferenceWith tail take takeRight takeRightWhile takeWhile union unionBy unionWith uniqueElements unzip unzipWith without xProd zip zipObject zipWith Browser arrayToHtmlList bottomVisible copyToClipboard createElement createEventHub currentURL detectDeviceType elementIsVisibleInViewport getScrollPosition getStyle hasClass hashBrowser hide httpsRedirect observeMutations off on onUserInputChange prefix recordAnimationFrames redirect runAsync scrollToTop setStyle show smoothScroll toggleClass UUIDGeneratorBrowser Date formatDuration getColonTimeFromDate getDaysDiffBetweenDates getMeridiemSuffixOfInteger tomorrow Function attempt bind bindKey chainAsync compose composeRight converge curry debounce defer delay functionName hz memoize negate once partial partialRight runPromisesInSeries sleep throttle times uncurry unfold Math approximatelyEqual average averageBy binomialCoefficient clampNumber degreesToRads digitize distance elo factorial fibonacci gcd geometricProgression hammingDistance inRange isDivisible isEven isPrime lcm luhnCheck maxBy median minBy percentile powerset primes radsToDegrees randomIntArrayInRange randomIntegerInRange randomNumberInRange round sdbm standardDeviation sum sumBy sumPower toSafeInteger Node atob btoa colorize hasFlags hashNode isTravisCI JSONToFile readFileLines untildify UUIDGeneratorNode Object bindAll deepClone defaults equals findKey findLastKey flattenObject forOwn forOwnRight functions get invertKeyValues lowercaseKeys mapKeys mapValues matches matchesWith merge nest objectFromPairs objectToPairs omit omitBy orderBy pick pickBy renameKeys shallowClone size transform truthCheckCollection unflattenObject String byteSize capitalize capitalizeEveryWord decapitalize escapeHTML escapeRegExp fromCamelCase isAbsoluteURL isAnagram isLowerCase isUpperCase mask pad palindrome pluralize removeNonASCII reverseString sortCharactersInString splitLines stringPermutations stripHTMLTags toCamelCase toKebabCase toSnakeCase truncateString unescapeHTML URLJoin words Type getType is isArrayLike isBoolean isEmpty isFunction isNil isNull isNumber isObject isObjectLike isPlainObject isPrimitive isPromiseLike isString isSymbol isUndefined isValidJSON Utility castArray cloneRegExp coalesce coalesceFactory extendHex getURLParameters hexToRGB httpGet httpPost isBrowser mostPerformant nthArg parseCookie prettyBytes randomHexColorCode RGBToHex serializeCookie timeTaken toCurrency toDecimalMark toOrdinalSuffix validateNumber yesNo Array all Returns true if the provided predicate function returns true for all elements in a collection, false otherwise.
Use Array.every() to test if all elements in the collection return true based on fn. Omit the second argument, fn, to use Boolean as a default.
const all = ( arr, fn = Boolean) => arr. every ( fn);
Show examples all ([ 4 , 2 , 3 ], x => x > 1 );
all ([ 1 , 2 , 3 ]);
📋 Copy to clipboard any Returns true if the provided predicate function returns true for at least one element in a collection, false otherwise.
Use Array.some() to test if any elements in the collection return true based on fn. Omit the second argument, fn, to use Boolean as a default.
const any = ( arr, fn = Boolean) => arr. some ( fn);
diff --git a/docs/beginner.html b/docs/beginner.html
index b5f2e3a2e..1f1d54337 100644
--- a/docs/beginner.html
+++ b/docs/beginner.html
@@ -56,7 +56,7 @@
document.getElementById('doc-drawer-checkbox').checked = false;
}
}, false);
- }Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
View collection
Snippets for Beginners The following section is aimed towards individuals who are at the start of their web developer journey. Each snippet in the next section is simple yet very educational for newcomers. This section is by no means a complete resource for learning modern JavaScript. However, it is enough to grasp some common concepts and use cases. We also strongly recommend checking out MDN web docs as a learning resource.
currentURL Returns the current URL.
Use window.location.href to get current URL.
const currentURL = () => window. location. href;
+ }Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.
View collection
Snippets for Beginners The following section is aimed towards individuals who are at the start of their web developer journey. Each snippet in the next section is simple yet very educational for newcomers. This section is by no means a complete resource for learning modern JavaScript. However, it is enough to grasp some common concepts and use cases. We also strongly recommend checking out MDN web docs as a learning resource.
currentURL Returns the current URL.
Use window.location.href to get current URL.
const currentURL = () => window. location. href;
Show examples currentURL ();
📋 Copy to clipboard 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.
const everyNth = ( arr, nth) => arr. filter (( e, i) => i % nth === nth - 1 );
Show examples everyNth ([ 1 , 2 , 3 , 4 , 5 , 6 ], 2 );
diff --git a/docs/browser.html b/docs/browser.html
index d1a5d28e4..f7ec0439a 100644
--- a/docs/browser.html
+++ b/docs/browser.html
@@ -79,7 +79,7 @@
document.getElementById('doc-drawer-checkbox').checked = false;
}
}, false);
- }
Adapter ary call collectInto flip over overArgs pipeAsyncFunctions pipeFunctions promisify rearg spreadOver unary Array all any bifurcate bifurcateBy chunk compact countBy countOccurrences deepFlatten difference differenceBy differenceWith drop dropRight dropRightWhile dropWhile everyNth filterNonUnique findLast findLastIndex flatten forEachRight groupBy head indexOfAll initial initialize2DArray initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues intersection intersectionBy intersectionWith isSorted join last longestItem mapObject maxN minN none nthElement offset partition permutations pull pullAtIndex pullAtValue pullBy reducedFilter reduceSuccessive reduceWhich remove sample sampleSize shuffle similarity sortedIndex sortedIndexBy sortedLastIndex sortedLastIndexBy stableSort symmetricDifference symmetricDifferenceBy symmetricDifferenceWith tail take takeRight takeRightWhile takeWhile union unionBy unionWith uniqueElements unzip unzipWith without xProd zip zipObject zipWith Browser arrayToHtmlList bottomVisible copyToClipboard createElement createEventHub currentURL detectDeviceType elementIsVisibleInViewport getScrollPosition getStyle hasClass hashBrowser hide httpsRedirect observeMutations off on onUserInputChange prefix recordAnimationFrames redirect runAsync scrollToTop setStyle show smoothScroll toggleClass UUIDGeneratorBrowser Date formatDuration getColonTimeFromDate getDaysDiffBetweenDates getMeridiemSuffixOfInteger tomorrow Function attempt bind bindKey chainAsync compose composeRight converge curry debounce defer delay functionName hz memoize negate once partial partialRight runPromisesInSeries sleep throttle times uncurry unfold Math approximatelyEqual average averageBy binomialCoefficient clampNumber degreesToRads digitize distance elo factorial fibonacci gcd geometricProgression hammingDistance inRange isDivisible isEven isPrime lcm luhnCheck maxBy median minBy percentile powerset primes radsToDegrees randomIntArrayInRange randomIntegerInRange randomNumberInRange round sdbm standardDeviation sum sumBy sumPower toSafeInteger Node atob btoa colorize hasFlags hashNode isTravisCI JSONToFile readFileLines untildify UUIDGeneratorNode Object bindAll deepClone defaults equals findKey findLastKey flattenObject forOwn forOwnRight functions get invertKeyValues lowercaseKeys mapKeys mapValues matches matchesWith merge nest objectFromPairs objectToPairs omit omitBy orderBy pick pickBy renameKeys shallowClone size transform truthCheckCollection unflattenObject String byteSize capitalize capitalizeEveryWord decapitalize escapeHTML escapeRegExp fromCamelCase isAbsoluteURL isAnagram isLowerCase isUpperCase mask pad palindrome pluralize removeNonASCII reverseString sortCharactersInString splitLines stringPermutations stripHTMLTags toCamelCase toKebabCase toSnakeCase truncateString unescapeHTML URLJoin words Type getType is isArrayLike isBoolean isEmpty isFunction isNil isNull isNumber isObject isObjectLike isPlainObject isPrimitive isPromiseLike isString isSymbol isUndefined isValidJSON Utility castArray cloneRegExp coalesce coalesceFactory extendHex getURLParameters hexToRGB httpGet httpPost isBrowser mostPerformant nthArg parseCookie prettyBytes randomHexColorCode RGBToHex serializeCookie timeTaken toCurrency toDecimalMark toOrdinalSuffix validateNumber yesNo Browser arrayToHtmlList Converts the given array elements into <li> tags and appends them to the list of the given id.
Use Array.map() and document.querySelector() to create a list of html tags.
const arrayToHtmlList = ( arr, listID) =>
+ }
Adapter ary call collectInto flip over overArgs pipeAsyncFunctions pipeFunctions promisify rearg spreadOver unary Array all any bifurcate bifurcateBy chunk compact countBy countOccurrences deepFlatten difference differenceBy differenceWith drop dropRight dropRightWhile dropWhile everyNth filterNonUnique findLast findLastIndex flatten forEachRight groupBy head indexOfAll initial initialize2DArray initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues intersection intersectionBy intersectionWith isSorted join last longestItem mapObject maxN minN none nthElement offset partition permutations pull pullAtIndex pullAtValue pullBy reducedFilter reduceSuccessive reduceWhich remove sample sampleSize shuffle similarity sortedIndex sortedIndexBy sortedLastIndex sortedLastIndexBy stableSort symmetricDifference symmetricDifferenceBy symmetricDifferenceWith tail take takeRight takeRightWhile takeWhile union unionBy unionWith uniqueElements unzip unzipWith without xProd zip zipObject zipWith Browser arrayToHtmlList bottomVisible copyToClipboard createElement createEventHub currentURL detectDeviceType elementIsVisibleInViewport getScrollPosition getStyle hasClass hashBrowser hide httpsRedirect observeMutations off on onUserInputChange prefix recordAnimationFrames redirect runAsync scrollToTop setStyle show smoothScroll toggleClass UUIDGeneratorBrowser Date formatDuration getColonTimeFromDate getDaysDiffBetweenDates getMeridiemSuffixOfInteger tomorrow Function attempt bind bindKey chainAsync compose composeRight converge curry debounce defer delay functionName hz memoize negate once partial partialRight runPromisesInSeries sleep throttle times uncurry unfold Math approximatelyEqual average averageBy binomialCoefficient clampNumber degreesToRads digitize distance elo factorial fibonacci gcd geometricProgression hammingDistance inRange isDivisible isEven isPrime lcm luhnCheck maxBy median minBy percentile powerset primes radsToDegrees randomIntArrayInRange randomIntegerInRange randomNumberInRange round sdbm standardDeviation sum sumBy sumPower toSafeInteger Node atob btoa colorize hasFlags hashNode isTravisCI JSONToFile readFileLines untildify UUIDGeneratorNode Object bindAll deepClone defaults equals findKey findLastKey flattenObject forOwn forOwnRight functions get invertKeyValues lowercaseKeys mapKeys mapValues matches matchesWith merge nest objectFromPairs objectToPairs omit omitBy orderBy pick pickBy renameKeys shallowClone size transform truthCheckCollection unflattenObject String byteSize capitalize capitalizeEveryWord decapitalize escapeHTML escapeRegExp fromCamelCase isAbsoluteURL isAnagram isLowerCase isUpperCase mask pad palindrome pluralize removeNonASCII reverseString sortCharactersInString splitLines stringPermutations stripHTMLTags toCamelCase toKebabCase toSnakeCase truncateString unescapeHTML URLJoin words Type getType is isArrayLike isBoolean isEmpty isFunction isNil isNull isNumber isObject isObjectLike isPlainObject isPrimitive isPromiseLike isString isSymbol isUndefined isValidJSON Utility castArray cloneRegExp coalesce coalesceFactory extendHex getURLParameters hexToRGB httpGet httpPost isBrowser mostPerformant nthArg parseCookie prettyBytes randomHexColorCode RGBToHex serializeCookie timeTaken toCurrency toDecimalMark toOrdinalSuffix validateNumber yesNo Browser arrayToHtmlList Converts the given array elements into <li> tags and appends them to the list of the given id.
Use Array.map() and document.querySelector() to create a list of html tags.
const arrayToHtmlList = ( arr, listID) =>
arr. map ( item => ( document. querySelector ( '#' + listID). innerHTML += `<li> ${ item} </li>` ));
Show examples arrayToHtmlList ([ 'item 1' , 'item 2' ], 'myListID' );
📋 Copy to clipboard 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.
const bottomVisible = () =>
diff --git a/docs/date.html b/docs/date.html
index 0e8d720de..5af4a4297 100644
--- a/docs/date.html
+++ b/docs/date.html
@@ -79,7 +79,7 @@
document.getElementById('doc-drawer-checkbox').checked = false;
}
}, false);
- }
Adapter ary call collectInto flip over overArgs pipeAsyncFunctions pipeFunctions promisify rearg spreadOver unary Array all any bifurcate bifurcateBy chunk compact countBy countOccurrences deepFlatten difference differenceBy differenceWith drop dropRight dropRightWhile dropWhile everyNth filterNonUnique findLast findLastIndex flatten forEachRight groupBy head indexOfAll initial initialize2DArray initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues intersection intersectionBy intersectionWith isSorted join last longestItem mapObject maxN minN none nthElement offset partition permutations pull pullAtIndex pullAtValue pullBy reducedFilter reduceSuccessive reduceWhich remove sample sampleSize shuffle similarity sortedIndex sortedIndexBy sortedLastIndex sortedLastIndexBy stableSort symmetricDifference symmetricDifferenceBy symmetricDifferenceWith tail take takeRight takeRightWhile takeWhile union unionBy unionWith uniqueElements unzip unzipWith without xProd zip zipObject zipWith Browser arrayToHtmlList bottomVisible copyToClipboard createElement createEventHub currentURL detectDeviceType elementIsVisibleInViewport getScrollPosition getStyle hasClass hashBrowser hide httpsRedirect observeMutations off on onUserInputChange prefix recordAnimationFrames redirect runAsync scrollToTop setStyle show smoothScroll toggleClass UUIDGeneratorBrowser Date formatDuration getColonTimeFromDate getDaysDiffBetweenDates getMeridiemSuffixOfInteger tomorrow Function attempt bind bindKey chainAsync compose composeRight converge curry debounce defer delay functionName hz memoize negate once partial partialRight runPromisesInSeries sleep throttle times uncurry unfold Math approximatelyEqual average averageBy binomialCoefficient clampNumber degreesToRads digitize distance elo factorial fibonacci gcd geometricProgression hammingDistance inRange isDivisible isEven isPrime lcm luhnCheck maxBy median minBy percentile powerset primes radsToDegrees randomIntArrayInRange randomIntegerInRange randomNumberInRange round sdbm standardDeviation sum sumBy sumPower toSafeInteger Node atob btoa colorize hasFlags hashNode isTravisCI JSONToFile readFileLines untildify UUIDGeneratorNode Object bindAll deepClone defaults equals findKey findLastKey flattenObject forOwn forOwnRight functions get invertKeyValues lowercaseKeys mapKeys mapValues matches matchesWith merge nest objectFromPairs objectToPairs omit omitBy orderBy pick pickBy renameKeys shallowClone size transform truthCheckCollection unflattenObject String byteSize capitalize capitalizeEveryWord decapitalize escapeHTML escapeRegExp fromCamelCase isAbsoluteURL isAnagram isLowerCase isUpperCase mask pad palindrome pluralize removeNonASCII reverseString sortCharactersInString splitLines stringPermutations stripHTMLTags toCamelCase toKebabCase toSnakeCase truncateString unescapeHTML URLJoin words Type getType is isArrayLike isBoolean isEmpty isFunction isNil isNull isNumber isObject isObjectLike isPlainObject isPrimitive isPromiseLike isString isSymbol isUndefined isValidJSON Utility castArray cloneRegExp coalesce coalesceFactory extendHex getURLParameters hexToRGB httpGet httpPost isBrowser mostPerformant nthArg parseCookie prettyBytes randomHexColorCode RGBToHex serializeCookie timeTaken toCurrency toDecimalMark toOrdinalSuffix validateNumber yesNo Date Returns the human readable format of the given number of milliseconds.
Divide ms with the appropriate values to obtain the appropriate values for day, hour, minute, second and millisecond. Use Object.entries() with Array.filter() to keep only non-zero values. Use Array.map() to create the string for each value, pluralizing appropriately. Use String.join(', ') to combine the values into a string.
const formatDuration = ms => {
+ }
Adapter ary call collectInto flip over overArgs pipeAsyncFunctions pipeFunctions promisify rearg spreadOver unary Array all any bifurcate bifurcateBy chunk compact countBy countOccurrences deepFlatten difference differenceBy differenceWith drop dropRight dropRightWhile dropWhile everyNth filterNonUnique findLast findLastIndex flatten forEachRight groupBy head indexOfAll initial initialize2DArray initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues intersection intersectionBy intersectionWith isSorted join last longestItem mapObject maxN minN none nthElement offset partition permutations pull pullAtIndex pullAtValue pullBy reducedFilter reduceSuccessive reduceWhich remove sample sampleSize shuffle similarity sortedIndex sortedIndexBy sortedLastIndex sortedLastIndexBy stableSort symmetricDifference symmetricDifferenceBy symmetricDifferenceWith tail take takeRight takeRightWhile takeWhile union unionBy unionWith uniqueElements unzip unzipWith without xProd zip zipObject zipWith Browser arrayToHtmlList bottomVisible copyToClipboard createElement createEventHub currentURL detectDeviceType elementIsVisibleInViewport getScrollPosition getStyle hasClass hashBrowser hide httpsRedirect observeMutations off on onUserInputChange prefix recordAnimationFrames redirect runAsync scrollToTop setStyle show smoothScroll toggleClass UUIDGeneratorBrowser Date formatDuration getColonTimeFromDate getDaysDiffBetweenDates getMeridiemSuffixOfInteger tomorrow Function attempt bind bindKey chainAsync compose composeRight converge curry debounce defer delay functionName hz memoize negate once partial partialRight runPromisesInSeries sleep throttle times uncurry unfold Math approximatelyEqual average averageBy binomialCoefficient clampNumber degreesToRads digitize distance elo factorial fibonacci gcd geometricProgression hammingDistance inRange isDivisible isEven isPrime lcm luhnCheck maxBy median minBy percentile powerset primes radsToDegrees randomIntArrayInRange randomIntegerInRange randomNumberInRange round sdbm standardDeviation sum sumBy sumPower toSafeInteger Node atob btoa colorize hasFlags hashNode isTravisCI JSONToFile readFileLines untildify UUIDGeneratorNode Object bindAll deepClone defaults equals findKey findLastKey flattenObject forOwn forOwnRight functions get invertKeyValues lowercaseKeys mapKeys mapValues matches matchesWith merge nest objectFromPairs objectToPairs omit omitBy orderBy pick pickBy renameKeys shallowClone size transform truthCheckCollection unflattenObject String byteSize capitalize capitalizeEveryWord decapitalize escapeHTML escapeRegExp fromCamelCase isAbsoluteURL isAnagram isLowerCase isUpperCase mask pad palindrome pluralize removeNonASCII reverseString sortCharactersInString splitLines stringPermutations stripHTMLTags toCamelCase toKebabCase toSnakeCase truncateString unescapeHTML URLJoin words Type getType is isArrayLike isBoolean isEmpty isFunction isNil isNull isNumber isObject isObjectLike isPlainObject isPrimitive isPromiseLike isString isSymbol isUndefined isValidJSON Utility castArray cloneRegExp coalesce coalesceFactory extendHex getURLParameters hexToRGB httpGet httpPost isBrowser mostPerformant nthArg parseCookie prettyBytes randomHexColorCode RGBToHex serializeCookie timeTaken toCurrency toDecimalMark toOrdinalSuffix validateNumber yesNo Date Returns the human readable format of the given number of milliseconds.
Divide ms with the appropriate values to obtain the appropriate values for day, hour, minute, second and millisecond. Use Object.entries() with Array.filter() to keep only non-zero values. Use Array.map() to create the string for each value, pluralizing appropriately. Use String.join(', ') to combine the values into a string.
const formatDuration = ms => {
if ( ms < 0 ) ms = - ms;
const time = {
day: Math. floor ( ms / 86400000 ),
diff --git a/docs/function.html b/docs/function.html
index 3ea23494b..8d5556a27 100644
--- a/docs/function.html
+++ b/docs/function.html
@@ -79,7 +79,7 @@
document.getElementById('doc-drawer-checkbox').checked = false;
}
}, false);
- }
Adapter ary call collectInto flip over overArgs pipeAsyncFunctions pipeFunctions promisify rearg spreadOver unary Array all any bifurcate bifurcateBy chunk compact countBy countOccurrences deepFlatten difference differenceBy differenceWith drop dropRight dropRightWhile dropWhile everyNth filterNonUnique findLast findLastIndex flatten forEachRight groupBy head indexOfAll initial initialize2DArray initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues intersection intersectionBy intersectionWith isSorted join last longestItem mapObject maxN minN none nthElement offset partition permutations pull pullAtIndex pullAtValue pullBy reducedFilter reduceSuccessive reduceWhich remove sample sampleSize shuffle similarity sortedIndex sortedIndexBy sortedLastIndex sortedLastIndexBy stableSort symmetricDifference symmetricDifferenceBy symmetricDifferenceWith tail take takeRight takeRightWhile takeWhile union unionBy unionWith uniqueElements unzip unzipWith without xProd zip zipObject zipWith Browser arrayToHtmlList bottomVisible copyToClipboard createElement createEventHub currentURL detectDeviceType elementIsVisibleInViewport getScrollPosition getStyle hasClass hashBrowser hide httpsRedirect observeMutations off on onUserInputChange prefix recordAnimationFrames redirect runAsync scrollToTop setStyle show smoothScroll toggleClass UUIDGeneratorBrowser Date formatDuration getColonTimeFromDate getDaysDiffBetweenDates getMeridiemSuffixOfInteger tomorrow Function attempt bind bindKey chainAsync compose composeRight converge curry debounce defer delay functionName hz memoize negate once partial partialRight runPromisesInSeries sleep throttle times uncurry unfold Math approximatelyEqual average averageBy binomialCoefficient clampNumber degreesToRads digitize distance elo factorial fibonacci gcd geometricProgression hammingDistance inRange isDivisible isEven isPrime lcm luhnCheck maxBy median minBy percentile powerset primes radsToDegrees randomIntArrayInRange randomIntegerInRange randomNumberInRange round sdbm standardDeviation sum sumBy sumPower toSafeInteger Node atob btoa colorize hasFlags hashNode isTravisCI JSONToFile readFileLines untildify UUIDGeneratorNode Object bindAll deepClone defaults equals findKey findLastKey flattenObject forOwn forOwnRight functions get invertKeyValues lowercaseKeys mapKeys mapValues matches matchesWith merge nest objectFromPairs objectToPairs omit omitBy orderBy pick pickBy renameKeys shallowClone size transform truthCheckCollection unflattenObject String byteSize capitalize capitalizeEveryWord decapitalize escapeHTML escapeRegExp fromCamelCase isAbsoluteURL isAnagram isLowerCase isUpperCase mask pad palindrome pluralize removeNonASCII reverseString sortCharactersInString splitLines stringPermutations stripHTMLTags toCamelCase toKebabCase toSnakeCase truncateString unescapeHTML URLJoin words Type getType is isArrayLike isBoolean isEmpty isFunction isNil isNull isNumber isObject isObjectLike isPlainObject isPrimitive isPromiseLike isString isSymbol isUndefined isValidJSON Utility castArray cloneRegExp coalesce coalesceFactory extendHex getURLParameters hexToRGB httpGet httpPost isBrowser mostPerformant nthArg parseCookie prettyBytes randomHexColorCode RGBToHex serializeCookie timeTaken toCurrency toDecimalMark toOrdinalSuffix validateNumber yesNo Function attempt Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.
Use a try... catch block to return either the result of the function or an appropriate error.
const attempt = ( fn, ... args) => {
+ }
Adapter ary call collectInto flip over overArgs pipeAsyncFunctions pipeFunctions promisify rearg spreadOver unary Array all any bifurcate bifurcateBy chunk compact countBy countOccurrences deepFlatten difference differenceBy differenceWith drop dropRight dropRightWhile dropWhile everyNth filterNonUnique findLast findLastIndex flatten forEachRight groupBy head indexOfAll initial initialize2DArray initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues intersection intersectionBy intersectionWith isSorted join last longestItem mapObject maxN minN none nthElement offset partition permutations pull pullAtIndex pullAtValue pullBy reducedFilter reduceSuccessive reduceWhich remove sample sampleSize shuffle similarity sortedIndex sortedIndexBy sortedLastIndex sortedLastIndexBy stableSort symmetricDifference symmetricDifferenceBy symmetricDifferenceWith tail take takeRight takeRightWhile takeWhile union unionBy unionWith uniqueElements unzip unzipWith without xProd zip zipObject zipWith Browser arrayToHtmlList bottomVisible copyToClipboard createElement createEventHub currentURL detectDeviceType elementIsVisibleInViewport getScrollPosition getStyle hasClass hashBrowser hide httpsRedirect observeMutations off on onUserInputChange prefix recordAnimationFrames redirect runAsync scrollToTop setStyle show smoothScroll toggleClass UUIDGeneratorBrowser Date formatDuration getColonTimeFromDate getDaysDiffBetweenDates getMeridiemSuffixOfInteger tomorrow Function attempt bind bindKey chainAsync compose composeRight converge curry debounce defer delay functionName hz memoize negate once partial partialRight runPromisesInSeries sleep throttle times uncurry unfold Math approximatelyEqual average averageBy binomialCoefficient clampNumber degreesToRads digitize distance elo factorial fibonacci gcd geometricProgression hammingDistance inRange isDivisible isEven isPrime lcm luhnCheck maxBy median minBy percentile powerset primes radsToDegrees randomIntArrayInRange randomIntegerInRange randomNumberInRange round sdbm standardDeviation sum sumBy sumPower toSafeInteger Node atob btoa colorize hasFlags hashNode isTravisCI JSONToFile readFileLines untildify UUIDGeneratorNode Object bindAll deepClone defaults equals findKey findLastKey flattenObject forOwn forOwnRight functions get invertKeyValues lowercaseKeys mapKeys mapValues matches matchesWith merge nest objectFromPairs objectToPairs omit omitBy orderBy pick pickBy renameKeys shallowClone size transform truthCheckCollection unflattenObject String byteSize capitalize capitalizeEveryWord decapitalize escapeHTML escapeRegExp fromCamelCase isAbsoluteURL isAnagram isLowerCase isUpperCase mask pad palindrome pluralize removeNonASCII reverseString sortCharactersInString splitLines stringPermutations stripHTMLTags toCamelCase toKebabCase toSnakeCase truncateString unescapeHTML URLJoin words Type getType is isArrayLike isBoolean isEmpty isFunction isNil isNull isNumber isObject isObjectLike isPlainObject isPrimitive isPromiseLike isString isSymbol isUndefined isValidJSON Utility castArray cloneRegExp coalesce coalesceFactory extendHex getURLParameters hexToRGB httpGet httpPost isBrowser mostPerformant nthArg parseCookie prettyBytes randomHexColorCode RGBToHex serializeCookie timeTaken toCurrency toDecimalMark toOrdinalSuffix validateNumber yesNo Function attempt Attempts to invoke a function with the provided arguments, returning either the result or the caught error object.
Use a try... catch block to return either the result of the function or an appropriate error.
const attempt = ( fn, ... args) => {
try {
return fn ( ... args);
} catch ( e ) {
diff --git a/docs/math.html b/docs/math.html
index bb82f4270..3dae0df3e 100644
--- a/docs/math.html
+++ b/docs/math.html
@@ -79,7 +79,7 @@
document.getElementById('doc-drawer-checkbox').checked = false;
}
}, false);
- }
Adapter ary call collectInto flip over overArgs pipeAsyncFunctions pipeFunctions promisify rearg spreadOver unary Array all any bifurcate bifurcateBy chunk compact countBy countOccurrences deepFlatten difference differenceBy differenceWith drop dropRight dropRightWhile dropWhile everyNth filterNonUnique findLast findLastIndex flatten forEachRight groupBy head indexOfAll initial initialize2DArray initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues intersection intersectionBy intersectionWith isSorted join last longestItem mapObject maxN minN none nthElement offset partition permutations pull pullAtIndex pullAtValue pullBy reducedFilter reduceSuccessive reduceWhich remove sample sampleSize shuffle similarity sortedIndex sortedIndexBy sortedLastIndex sortedLastIndexBy stableSort symmetricDifference symmetricDifferenceBy symmetricDifferenceWith tail take takeRight takeRightWhile takeWhile union unionBy unionWith uniqueElements unzip unzipWith without xProd zip zipObject zipWith Browser arrayToHtmlList bottomVisible copyToClipboard createElement createEventHub currentURL detectDeviceType elementIsVisibleInViewport getScrollPosition getStyle hasClass hashBrowser hide httpsRedirect observeMutations off on onUserInputChange prefix recordAnimationFrames redirect runAsync scrollToTop setStyle show smoothScroll toggleClass UUIDGeneratorBrowser Date formatDuration getColonTimeFromDate getDaysDiffBetweenDates getMeridiemSuffixOfInteger tomorrow Function attempt bind bindKey chainAsync compose composeRight converge curry debounce defer delay functionName hz memoize negate once partial partialRight runPromisesInSeries sleep throttle times uncurry unfold Math approximatelyEqual average averageBy binomialCoefficient clampNumber degreesToRads digitize distance elo factorial fibonacci gcd geometricProgression hammingDistance inRange isDivisible isEven isPrime lcm luhnCheck maxBy median minBy percentile powerset primes radsToDegrees randomIntArrayInRange randomIntegerInRange randomNumberInRange round sdbm standardDeviation sum sumBy sumPower toSafeInteger Node atob btoa colorize hasFlags hashNode isTravisCI JSONToFile readFileLines untildify UUIDGeneratorNode Object bindAll deepClone defaults equals findKey findLastKey flattenObject forOwn forOwnRight functions get invertKeyValues lowercaseKeys mapKeys mapValues matches matchesWith merge nest objectFromPairs objectToPairs omit omitBy orderBy pick pickBy renameKeys shallowClone size transform truthCheckCollection unflattenObject String byteSize capitalize capitalizeEveryWord decapitalize escapeHTML escapeRegExp fromCamelCase isAbsoluteURL isAnagram isLowerCase isUpperCase mask pad palindrome pluralize removeNonASCII reverseString sortCharactersInString splitLines stringPermutations stripHTMLTags toCamelCase toKebabCase toSnakeCase truncateString unescapeHTML URLJoin words Type getType is isArrayLike isBoolean isEmpty isFunction isNil isNull isNumber isObject isObjectLike isPlainObject isPrimitive isPromiseLike isString isSymbol isUndefined isValidJSON Utility castArray cloneRegExp coalesce coalesceFactory extendHex getURLParameters hexToRGB httpGet httpPost isBrowser mostPerformant nthArg parseCookie prettyBytes randomHexColorCode RGBToHex serializeCookie timeTaken toCurrency toDecimalMark toOrdinalSuffix validateNumber yesNo Math approximatelyEqual Checks if two numbers are approximately equal to each other.
Use Math.abs() to compare the absolute difference of the two values to epsilon. Omit the third parameter, epsilon, to use a default value of 0.001.
const approximatelyEqual = ( v1, v2, epsilon = 0.001 ) => Math. abs ( v1 - v2) < epsilon;
+ }
Adapter ary call collectInto flip over overArgs pipeAsyncFunctions pipeFunctions promisify rearg spreadOver unary Array all any bifurcate bifurcateBy chunk compact countBy countOccurrences deepFlatten difference differenceBy differenceWith drop dropRight dropRightWhile dropWhile everyNth filterNonUnique findLast findLastIndex flatten forEachRight groupBy head indexOfAll initial initialize2DArray initializeArrayWithRange initializeArrayWithRangeRight initializeArrayWithValues intersection intersectionBy intersectionWith isSorted join last longestItem mapObject maxN minN none nthElement offset partition permutations pull pullAtIndex pullAtValue pullBy reducedFilter reduceSuccessive reduceWhich remove sample sampleSize shuffle similarity sortedIndex sortedIndexBy sortedLastIndex sortedLastIndexBy stableSort symmetricDifference symmetricDifferenceBy symmetricDifferenceWith tail take takeRight takeRightWhile takeWhile union unionBy unionWith uniqueElements unzip unzipWith without xProd zip zipObject zipWith Browser arrayToHtmlList bottomVisible copyToClipboard createElement createEventHub currentURL detectDeviceType elementIsVisibleInViewport getScrollPosition getStyle hasClass hashBrowser hide httpsRedirect observeMutations off on onUserInputChange prefix recordAnimationFrames redirect runAsync scrollToTop setStyle show smoothScroll toggleClass UUIDGeneratorBrowser Date formatDuration getColonTimeFromDate getDaysDiffBetweenDates getMeridiemSuffixOfInteger tomorrow Function attempt bind bindKey chainAsync compose composeRight converge curry debounce defer delay functionName hz memoize negate once partial partialRight runPromisesInSeries sleep throttle times uncurry unfold Math approximatelyEqual average averageBy binomialCoefficient clampNumber degreesToRads digitize distance elo factorial fibonacci gcd geometricProgression hammingDistance inRange isDivisible isEven isPrime lcm luhnCheck maxBy median minBy percentile powerset primes radsToDegrees randomIntArrayInRange randomIntegerInRange randomNumberInRange round sdbm standardDeviation sum sumBy sumPower toSafeInteger Node atob btoa colorize hasFlags hashNode isTravisCI JSONToFile readFileLines untildify UUIDGeneratorNode Object bindAll deepClone defaults equals findKey findLastKey flattenObject forOwn forOwnRight functions get invertKeyValues lowercaseKeys mapKeys mapValues matches matchesWith merge nest objectFromPairs objectToPairs omit omitBy orderBy pick pickBy renameKeys shallowClone size transform truthCheckCollection unflattenObject String byteSize capitalize capitalizeEveryWord decapitalize escapeHTML escapeRegExp fromCamelCase isAbsoluteURL isAnagram isLowerCase isUpperCase mask pad palindrome pluralize removeNonASCII reverseString sortCharactersInString splitLines stringPermutations stripHTMLTags toCamelCase toKebabCase toSnakeCase truncateString unescapeHTML URLJoin words Type getType is isArrayLike isBoolean isEmpty isFunction isNil isNull isNumber isObject isObjectLike isPlainObject isPrimitive isPromiseLike isString isSymbol isUndefined isValidJSON Utility castArray cloneRegExp coalesce coalesceFactory extendHex getURLParameters hexToRGB httpGet httpPost isBrowser mostPerformant nthArg parseCookie prettyBytes randomHexColorCode RGBToHex serializeCookie timeTaken toCurrency toDecimalMark toOrdinalSuffix validateNumber yesNo Math approximatelyEqual Checks if two numbers are approximately equal to each other.
Use Math.abs() to compare the absolute difference of the two values to epsilon. Omit the third parameter, epsilon, to use a default value of 0.001.
const approximatelyEqual = ( v1, v2, epsilon = 0.001 ) => Math. abs ( v1 - v2) < epsilon;
Show examples approximatelyEqual ( Math. PI / 2.0 , 1.5708 );
📋 Copy to clipboard average Returns the average of two or more numbers.
Use Array.reduce() to add each value to an accumulator, initialized with a value of 0, divide by the length of the array.
const average = ( ... nums) => [ ... nums]. reduce (( acc, val) => acc + val, 0 ) / nums. length;
Show examples average ( ... [ 1 , 2 , 3 ]);
diff --git a/docs/node.html b/docs/node.html
index fdff7ce18..f56a103b6 100644
--- a/docs/node.html
+++ b/docs/node.html
@@ -79,7 +79,7 @@
document.getElementById('doc-drawer-checkbox').checked = false;
}
}, false);
- }