Merge branch 'master' into add-permuteAll

This commit is contained in:
Angelos Chalaris
2018-02-19 15:55:09 +02:00
committed by GitHub
73 changed files with 1222 additions and 103 deletions

18
.npmignore Normal file
View File

@ -0,0 +1,18 @@
snippet-template.md
tag_database
travis.log
CONTRIBUTING.md
COLLABORATING.md
CODE_OF_CONDUCT.md
.travis.yml
.mdlrc.style.rb
.mdlrc
.codeclimate.yml
test/*
static-parts/*
snippets_archive/*
scripts/*
locale/*
docs/*
.travis/*
.github/*

334
README.md
View File

@ -98,6 +98,10 @@ average(1, 2, 3);
<details>
<summary>View contents</summary>
* [`all`](#all)
* [`any`](#any)
* [`bifurcate`](#bifurcate)
* [`bifurcateBy`](#bifurcateby)
* [`chunk`](#chunk)
* [`compact`](#compact)
* [`countBy`](#countby)
@ -134,6 +138,7 @@ average(1, 2, 3);
* [`mapObject`](#mapobject-)
* [`maxN`](#maxn)
* [`minN`](#minn)
* [`none`](#none)
* [`nthElement`](#nthelement)
* [`partition`](#partition)
* [`pull`](#pull)
@ -152,6 +157,7 @@ average(1, 2, 3);
* [`sortedIndexBy`](#sortedindexby)
* [`sortedLastIndex`](#sortedlastindex)
* [`sortedLastIndexBy`](#sortedlastindexby)
* [`stableSort`](#stablesort-)
* [`symmetricDifference`](#symmetricdifference)
* [`symmetricDifferenceBy`](#symmetricdifferenceby)
* [`symmetricDifferenceWith`](#symmetricdifferencewith)
@ -246,6 +252,7 @@ average(1, 2, 3);
* [`sleep`](#sleep)
* [`throttle`](#throttle)
* [`times`](#times)
* [`uncurry`](#uncurry)
* [`unfold`](#unfold)
</details>
@ -255,9 +262,12 @@ average(1, 2, 3);
<details>
<summary>View contents</summary>
* [`approximatelyEqual`](#approximatelyequal)
* [`average`](#average)
* [`averageBy`](#averageby)
* [`binomialCoefficient`](#binomialcoefficient)
* [`clampNumber`](#clampnumber)
* [`degreesToRads`](#degreestorads)
* [`digitize`](#digitize)
* [`distance`](#distance)
* [`elo`](#elo-)
@ -278,6 +288,7 @@ average(1, 2, 3);
* [`percentile`](#percentile)
* [`powerset`](#powerset)
* [`primes`](#primes)
* [`radsToDegrees`](#radstodegrees)
* [`randomIntArrayInRange`](#randomintarrayinrange)
* [`randomIntegerInRange`](#randomintegerinrange)
* [`randomNumberInRange`](#randomnumberinrange)
@ -421,6 +432,7 @@ average(1, 2, 3);
* [`hexToRGB`](#hextorgb-)
* [`httpGet`](#httpget)
* [`httpPost`](#httppost)
* [`mostPerformant`](#mostperformant)
* [`nthArg`](#ntharg)
* [`parseCookie`](#parsecookie)
* [`prettyBytes`](#prettybytes)
@ -760,6 +772,100 @@ const unary = fn => val => fn(val);
---
## 📚 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.
```js
const all = (arr, fn = Boolean) => arr.every(fn);
```
<details>
<summary>Examples</summary>
```js
all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### 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.
```js
const any = (arr, fn = Boolean) => arr.some(fn);
```
<details>
<summary>Examples</summary>
```js
any([0, 1, 2, 0], x => x >= 2); // true
any([0, 0, 1, 0]); // true
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### bifurcate
Splits values into two groups. If an element in `filter` is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
Use `Array.reduce()` and `Array.push()` to add elements to groups, based on `filter`.
```js
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
```
<details>
<summary>Examples</summary>
```js
bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### bifurcateBy
Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.
Use `Array.reduce()` and `Array.push()` to add elements to groups, based on the value returned by `fn` for each element.
```js
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
```
<details>
<summary>Examples</summary>
```js
bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### chunk
Chunks an array into smaller arrays of a specified size.
@ -1665,6 +1771,30 @@ minN([1, 2, 3], 2); // [1,2]
<br>[⬆ Back to top](#table-of-contents)
### none
Returns `true` if the provided predicate function returns `false` for all elements 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.
```js
const none = (arr, fn = Boolean) => !arr.some(fn);
```
<details>
<summary>Examples</summary>
```js
none([0, 1, 3, 0], x => x == 2); // true
none([0, 0, 0]); // true
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### nthElement
Returns the nth element of an array.
@ -2199,6 +2329,36 @@ sortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o => o.x); // 1
<br>[⬆ Back to top](#table-of-contents)
### stableSort ![advanced](/advanced.svg)
Performs stable sorting of an array, preserving the initial indexes of items when their values are the same.
Does not mutate the original array, but returns a new array instead.
Use `Array.map()` to pair each element of the input array with its corresponding index.
Use `Array.sort()` and a `compare` function to sort the list, preserving their initial order if the items compared are equal.
Use `Array.map()` to convert back to the initial array items.
```js
const stableSort = (arr, compare) =>
arr
.map((item, index) => ({ item, index }))
.sort((a, b) => compare(a.item, b.item) || a.index - b.index)
.map(({ item }) => item);
```
<details>
<summary>Examples</summary>
```js
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const stable = stableSort(arr, () => 0); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### symmetricDifference
Returns the symmetric difference between two arrays.
@ -4199,6 +4359,38 @@ console.log(output); // 01234
<br>[⬆ Back to top](#table-of-contents)
### uncurry
Uncurries a function up to depth `n`.
Return a variadic function.
Use `Array.reduce()` on the provided arguments to call each subsequent curry level of the function.
If the `length` of the provided arguments is less than `n` throw an error.
Otherwise, call `fn` with the proper amount of arguments, using `Array.slice(0, n)`.
Omit the second argument, `n`, to uncurry up to depth `1`.
```js
const uncurry = (fn, n = 1) => (...args) => {
const next = acc => args => args.reduce((x, y) => x(y), acc);
if (n > args.length) throw new RangeError('Arguments too few!');
return next(fn)(args.slice(0, n));
};
```
<details>
<summary>Examples</summary>
```js
const add = x => y => z => x + y + z;
const uncurriedAdd = uncurry(add, 3);
uncurriedAdd(1, 2, 3); // 6
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### unfold
Builds an array, using an iterator function and an initial seed value.
@ -4230,6 +4422,29 @@ unfold(f, 10); // [-10, -20, -30, -40, -50]
---
## ➗ 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`.
```js
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
```
<details>
<summary>Examples</summary>
```js
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### average
Returns the average of two or more numbers.
@ -4278,6 +4493,41 @@ averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5
<br>[⬆ Back to top](#table-of-contents)
### binomialCoefficient
Evaluates the binomial coefficient of two integers `n` and `k`.
Use `Number.isNaN()` to check if any of the two values is `NaN`.
Check if `k` is less than `0`, greater than or equal to `n`, equal to `1` or `n - 1` and return the appropriate result.
Check if `n - k` is less than `k` and switch their values accordingly.
Loop from `2` through `k` and calculate the binomial coefficient.
Use `Math.round()` to account for rounding errors in the calculation.
```js
const binomialCoefficient = (n, k) => {
if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
if (k < 0 || k > n) return 0;
if (k === 0 || k === n) return 1;
if (k === 1 || k === n - 1) return n;
if (n - k < k) k = n - k;
let res = n;
for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
return Math.round(res);
};
```
<details>
<summary>Examples</summary>
```js
binomialCoefficient(8, 2); // 28
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### clampNumber
Clamps `num` within the inclusive range specified by the boundary values `a` and `b`.
@ -4302,6 +4552,28 @@ clampNumber(1, -1, -5); // -1
<br>[⬆ Back to top](#table-of-contents)
### degreesToRads
Converts an angle from degrees to radians.
Use `Math.PI` and the degree to radian formula to convert the angle from degrees to radians.
```js
const degreesToRads = deg => deg * Math.PI / 180.0;
```
<details>
<summary>Examples</summary>
```js
degreesToRads(90.0); // ~1.5708
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### digitize
Converts a number to an array of digits.
@ -4850,6 +5122,28 @@ primes(10); // [2,3,5,7]
<br>[⬆ Back to top](#table-of-contents)
### radsToDegrees
Converts an angle from radians to degrees.
Use `Math.PI` and the radian to degree formula to convert the angle from radians to degrees.
```js
const radsToDegrees = rad => rad * 180.0 / Math.PI;
```
<details>
<summary>Examples</summary>
```js
radsToDegrees(Math.PI / 2); // 90
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### randomIntArrayInRange
Returns an array of n random integers in the specified range.
@ -7719,6 +8013,46 @@ Logs: {
<br>[⬆ Back to top](#table-of-contents)
### mostPerformant
Returns the index of the function in an array of functions which executed the fastest.
Use `Array.map()` to generate an array where each value is the total time taken to execute the function after `iterations` times. Use the difference in `performance.now()` values before and after to get the total time in milliseconds to a high degree of accuracy.
Use `Math.min()` to find the minimum execution time, and return the index of that shortest time which corresponds to the index of the most performant function.
Omit the second argument, `iterations`, to use a default of 10,000 iterations. The more iterations, the more reliable the result but the longer it will take.
```js
const mostPerformant = (fns, iterations = 10000) => {
const times = fns.map(fn => {
const before = performance.now();
for (let i = 0; i < iterations; i++) fn();
return performance.now() - before;
});
return times.indexOf(Math.min(...times));
};
```
<details>
<summary>Examples</summary>
```js
mostPerformant([
() => {
// Loops through the entire array before returning `false`
[1, 2, 3, 4, 5, 6, 7, 8, 9, '10'].every(el => typeof el === 'number');
},
() => {
// Only needs to reach index `1` before returning false
[1, '2', 3, 4, 5, 6, 7, 8, 9, 10].every(el => typeof el === 'number');
}
]); // 1
```
</details>
<br>[⬆ Back to top](#table-of-contents)
### nthArg
Creates a function that gets the argument at index `n`. If `n` is negative, the nth argument from the end is returned.

202
dist/_30s.es5.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

52
dist/_30s.esm.js vendored
View File

@ -25,6 +25,8 @@ const UUIDGeneratorNode = () =>
(c ^ (crypto$1.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
);
const all = (arr, fn = Boolean) => arr.every(fn);
const anagrams = str => {
if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
return str
@ -36,6 +38,10 @@ const anagrams = str => {
);
};
const any = (arr, fn = Boolean) => arr.some(fn);
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
const arrayToHtmlList = (arr, listID) =>
arr.map(item => (document.querySelector('#' + listID).innerHTML += `<li>${item}</li>`));
@ -57,6 +63,12 @@ const averageBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
arr.length;
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
const bind = (fn, context, ...args) =>
function() {
return fn.apply(context, args.concat(...arguments));
@ -75,6 +87,17 @@ const bindKey = (context, fn, ...args) =>
return context[fn].apply(context, args.concat(...arguments));
};
const binomialCoefficient = (n, k) => {
if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
if (k < 0 || k > n) return 0;
if (k === 0 || k === n) return 1;
if (k === 1 || k === n - 1) return n;
if (n - k < k) k = n - k;
let res = n;
for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
return Math.round(res);
};
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
@ -217,6 +240,8 @@ const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
const degreesToRads = deg => deg * Math.PI / 180.0;
const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
const detectDeviceType = () =>
@ -752,8 +777,19 @@ const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : v
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
const mostPerformant = (fns, iterations = 10000) => {
const times = fns.map(fn => {
const before = performance.now();
for (let i = 0; i < iterations; i++) fn();
return performance.now() - before;
});
return times.indexOf(Math.min(...times));
};
const negate = func => (...args) => !func(...args);
const none = (arr, fn = Boolean) => !arr.some(fn);
const nthArg = n => (...args) => args.slice(n)[0];
const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
@ -952,6 +988,8 @@ const pullBy = (arr, ...args) => {
pulled.forEach(v => arr.push(v));
};
const radsToDegrees = rad => rad * 180.0 / Math.PI;
const randomHexColorCode = () => {
let n = (Math.random() * 0xfffff * 1000000).toString(16);
return '#' + n.slice(0, 6);
@ -1122,6 +1160,12 @@ const splitLines = str => str.split(/\r?\n/);
const spreadOver = fn => argsArr => fn(...argsArr);
const stableSort = (arr, compare) =>
arr
.map((item, index) => ({ item, index }))
.sort((a, b) => compare(a.item, b.item) || a.index - b.index)
.map(({ item }) => item);
const standardDeviation = (arr, usePopulation = false) => {
const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length;
return Math.sqrt(
@ -1272,6 +1316,12 @@ const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pr
const unary = fn => val => fn(val);
const uncurry = (fn, n = 1) => (...args) => {
const next = acc => args => args.reduce((x, y) => x(y), acc);
if (n > args.length) throw new RangeError('Arguments too few!');
return next(fn)(args.slice(0, n));
};
const unescapeHTML = str =>
str.replace(
/&amp;|&lt;|&gt;|&#39;|&quot;/g,
@ -1373,6 +1423,6 @@ const zipWith = (...arrays) => {
return fn ? result.map(arr => fn(...arr)) : result;
};
var imports = {JSONToFile,RGBToHex,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,ary,atob,attempt,average,averageBy,bind,bindAll,bindKey,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,composeRight,converge,copyToClipboard,countBy,countOccurrences,createElement,createEventHub,currentURL,curry,debounce,decapitalize,deepClone,deepFlatten,defaults,defer,delay,detectDeviceType,difference,differenceBy,differenceWith,digitize,distance,drop,dropRight,dropRightWhile,dropWhile,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,findKey,findLast,findLastIndex,findLastKey,flatten,flattenObject,flip,forEachRight,forOwn,forOwnRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getColonTimeFromDate,getDaysDiffBetweenDates,getMeridiemSuffixOfInteger,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,inRange,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,intersection,intersectionBy,intersectionWith,invertKeyValues,is,isAbsoluteURL,isArrayLike,isBoolean,isDivisible,isEmpty,isEven,isFunction,isLowerCase,isNil,isNull,isNumber,isObject,isObjectLike,isPlainObject,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapValues,mask,matches,matchesWith,maxBy,maxN,median,memoize,merge,minBy,minN,negate,nthArg,nthElement,objectFromPairs,objectToPairs,observeMutations,off,omit,omitBy,on,onUserInputChange,once,orderBy,over,overArgs,palindrome,parseCookie,partial,partialRight,partition,percentile,pick,pickBy,pipeAsyncFunctions,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,rearg,redirect,reduceSuccessive,reduceWhich,reducedFilter,remove,removeNonASCII,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,serializeCookie,setStyle,shallowClone,show,shuffle,similarity,size,sleep,sortCharactersInString,sortedIndex,sortedIndexBy,sortedLastIndex,sortedLastIndexBy,splitLines,spreadOver,standardDeviation,stripHTMLTags,sum,sumBy,sumPower,symmetricDifference,symmetricDifferenceBy,symmetricDifferenceWith,tail,take,takeRight,takeRightWhile,takeWhile,throttle,timeTaken,times,toCamelCase,toCurrency,toDecimalMark,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toggleClass,tomorrow,transform,truncateString,truthCheckCollection,unary,unescapeHTML,unflattenObject,unfold,union,unionBy,unionWith,uniqueElements,untildify,unzip,unzipWith,validateNumber,without,words,xProd,yesNo,zip,zipObject,zipWith,}
var imports = {JSONToFile,RGBToHex,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,all,anagrams,any,approximatelyEqual,arrayToHtmlList,ary,atob,attempt,average,averageBy,bifurcate,bifurcateBy,bind,bindAll,bindKey,binomialCoefficient,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,composeRight,converge,copyToClipboard,countBy,countOccurrences,createElement,createEventHub,currentURL,curry,debounce,decapitalize,deepClone,deepFlatten,defaults,defer,degreesToRads,delay,detectDeviceType,difference,differenceBy,differenceWith,digitize,distance,drop,dropRight,dropRightWhile,dropWhile,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,findKey,findLast,findLastIndex,findLastKey,flatten,flattenObject,flip,forEachRight,forOwn,forOwnRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getColonTimeFromDate,getDaysDiffBetweenDates,getMeridiemSuffixOfInteger,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,inRange,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,intersection,intersectionBy,intersectionWith,invertKeyValues,is,isAbsoluteURL,isArrayLike,isBoolean,isDivisible,isEmpty,isEven,isFunction,isLowerCase,isNil,isNull,isNumber,isObject,isObjectLike,isPlainObject,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapValues,mask,matches,matchesWith,maxBy,maxN,median,memoize,merge,minBy,minN,mostPerformant,negate,none,nthArg,nthElement,objectFromPairs,objectToPairs,observeMutations,off,omit,omitBy,on,onUserInputChange,once,orderBy,over,overArgs,palindrome,parseCookie,partial,partialRight,partition,percentile,pick,pickBy,pipeAsyncFunctions,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,radsToDegrees,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,rearg,redirect,reduceSuccessive,reduceWhich,reducedFilter,remove,removeNonASCII,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,serializeCookie,setStyle,shallowClone,show,shuffle,similarity,size,sleep,sortCharactersInString,sortedIndex,sortedIndexBy,sortedLastIndex,sortedLastIndexBy,splitLines,spreadOver,stableSort,standardDeviation,stripHTMLTags,sum,sumBy,sumPower,symmetricDifference,symmetricDifferenceBy,symmetricDifferenceWith,tail,take,takeRight,takeRightWhile,takeWhile,throttle,timeTaken,times,toCamelCase,toCurrency,toDecimalMark,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toggleClass,tomorrow,transform,truncateString,truthCheckCollection,unary,uncurry,unescapeHTML,unflattenObject,unfold,union,unionBy,unionWith,uniqueElements,untildify,unzip,unzipWith,validateNumber,without,words,xProd,yesNo,zip,zipObject,zipWith,}
export default imports;

52
dist/_30s.js vendored
View File

@ -31,6 +31,8 @@ const UUIDGeneratorNode = () =>
(c ^ (crypto$1.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
);
const all = (arr, fn = Boolean) => arr.every(fn);
const anagrams = str => {
if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
return str
@ -42,6 +44,10 @@ const anagrams = str => {
);
};
const any = (arr, fn = Boolean) => arr.some(fn);
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
const arrayToHtmlList = (arr, listID) =>
arr.map(item => (document.querySelector('#' + listID).innerHTML += `<li>${item}</li>`));
@ -63,6 +69,12 @@ const averageBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
arr.length;
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
const bind = (fn, context, ...args) =>
function() {
return fn.apply(context, args.concat(...arguments));
@ -81,6 +93,17 @@ const bindKey = (context, fn, ...args) =>
return context[fn].apply(context, args.concat(...arguments));
};
const binomialCoefficient = (n, k) => {
if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
if (k < 0 || k > n) return 0;
if (k === 0 || k === n) return 1;
if (k === 1 || k === n - 1) return n;
if (n - k < k) k = n - k;
let res = n;
for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
return Math.round(res);
};
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
@ -223,6 +246,8 @@ const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
const degreesToRads = deg => deg * Math.PI / 180.0;
const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
const detectDeviceType = () =>
@ -758,8 +783,19 @@ const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : v
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
const mostPerformant = (fns, iterations = 10000) => {
const times = fns.map(fn => {
const before = performance.now();
for (let i = 0; i < iterations; i++) fn();
return performance.now() - before;
});
return times.indexOf(Math.min(...times));
};
const negate = func => (...args) => !func(...args);
const none = (arr, fn = Boolean) => !arr.some(fn);
const nthArg = n => (...args) => args.slice(n)[0];
const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
@ -958,6 +994,8 @@ const pullBy = (arr, ...args) => {
pulled.forEach(v => arr.push(v));
};
const radsToDegrees = rad => rad * 180.0 / Math.PI;
const randomHexColorCode = () => {
let n = (Math.random() * 0xfffff * 1000000).toString(16);
return '#' + n.slice(0, 6);
@ -1128,6 +1166,12 @@ const splitLines = str => str.split(/\r?\n/);
const spreadOver = fn => argsArr => fn(...argsArr);
const stableSort = (arr, compare) =>
arr
.map((item, index) => ({ item, index }))
.sort((a, b) => compare(a.item, b.item) || a.index - b.index)
.map(({ item }) => item);
const standardDeviation = (arr, usePopulation = false) => {
const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length;
return Math.sqrt(
@ -1278,6 +1322,12 @@ const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pr
const unary = fn => val => fn(val);
const uncurry = (fn, n = 1) => (...args) => {
const next = acc => args => args.reduce((x, y) => x(y), acc);
if (n > args.length) throw new RangeError('Arguments too few!');
return next(fn)(args.slice(0, n));
};
const unescapeHTML = str =>
str.replace(
/&amp;|&lt;|&gt;|&#39;|&quot;/g,
@ -1379,7 +1429,7 @@ const zipWith = (...arrays) => {
return fn ? result.map(arr => fn(...arr)) : result;
};
var imports = {JSONToFile,RGBToHex,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,ary,atob,attempt,average,averageBy,bind,bindAll,bindKey,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,composeRight,converge,copyToClipboard,countBy,countOccurrences,createElement,createEventHub,currentURL,curry,debounce,decapitalize,deepClone,deepFlatten,defaults,defer,delay,detectDeviceType,difference,differenceBy,differenceWith,digitize,distance,drop,dropRight,dropRightWhile,dropWhile,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,findKey,findLast,findLastIndex,findLastKey,flatten,flattenObject,flip,forEachRight,forOwn,forOwnRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getColonTimeFromDate,getDaysDiffBetweenDates,getMeridiemSuffixOfInteger,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,inRange,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,intersection,intersectionBy,intersectionWith,invertKeyValues,is,isAbsoluteURL,isArrayLike,isBoolean,isDivisible,isEmpty,isEven,isFunction,isLowerCase,isNil,isNull,isNumber,isObject,isObjectLike,isPlainObject,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapValues,mask,matches,matchesWith,maxBy,maxN,median,memoize,merge,minBy,minN,negate,nthArg,nthElement,objectFromPairs,objectToPairs,observeMutations,off,omit,omitBy,on,onUserInputChange,once,orderBy,over,overArgs,palindrome,parseCookie,partial,partialRight,partition,percentile,pick,pickBy,pipeAsyncFunctions,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,rearg,redirect,reduceSuccessive,reduceWhich,reducedFilter,remove,removeNonASCII,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,serializeCookie,setStyle,shallowClone,show,shuffle,similarity,size,sleep,sortCharactersInString,sortedIndex,sortedIndexBy,sortedLastIndex,sortedLastIndexBy,splitLines,spreadOver,standardDeviation,stripHTMLTags,sum,sumBy,sumPower,symmetricDifference,symmetricDifferenceBy,symmetricDifferenceWith,tail,take,takeRight,takeRightWhile,takeWhile,throttle,timeTaken,times,toCamelCase,toCurrency,toDecimalMark,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toggleClass,tomorrow,transform,truncateString,truthCheckCollection,unary,unescapeHTML,unflattenObject,unfold,union,unionBy,unionWith,uniqueElements,untildify,unzip,unzipWith,validateNumber,without,words,xProd,yesNo,zip,zipObject,zipWith,}
var imports = {JSONToFile,RGBToHex,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,all,anagrams,any,approximatelyEqual,arrayToHtmlList,ary,atob,attempt,average,averageBy,bifurcate,bifurcateBy,bind,bindAll,bindKey,binomialCoefficient,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,composeRight,converge,copyToClipboard,countBy,countOccurrences,createElement,createEventHub,currentURL,curry,debounce,decapitalize,deepClone,deepFlatten,defaults,defer,degreesToRads,delay,detectDeviceType,difference,differenceBy,differenceWith,digitize,distance,drop,dropRight,dropRightWhile,dropWhile,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,findKey,findLast,findLastIndex,findLastKey,flatten,flattenObject,flip,forEachRight,forOwn,forOwnRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getColonTimeFromDate,getDaysDiffBetweenDates,getMeridiemSuffixOfInteger,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,inRange,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,intersection,intersectionBy,intersectionWith,invertKeyValues,is,isAbsoluteURL,isArrayLike,isBoolean,isDivisible,isEmpty,isEven,isFunction,isLowerCase,isNil,isNull,isNumber,isObject,isObjectLike,isPlainObject,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapValues,mask,matches,matchesWith,maxBy,maxN,median,memoize,merge,minBy,minN,mostPerformant,negate,none,nthArg,nthElement,objectFromPairs,objectToPairs,observeMutations,off,omit,omitBy,on,onUserInputChange,once,orderBy,over,overArgs,palindrome,parseCookie,partial,partialRight,partition,percentile,pick,pickBy,pipeAsyncFunctions,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,radsToDegrees,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,rearg,redirect,reduceSuccessive,reduceWhich,reducedFilter,remove,removeNonASCII,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,serializeCookie,setStyle,shallowClone,show,shuffle,similarity,size,sleep,sortCharactersInString,sortedIndex,sortedIndexBy,sortedLastIndex,sortedLastIndexBy,splitLines,spreadOver,stableSort,standardDeviation,stripHTMLTags,sum,sumBy,sumPower,symmetricDifference,symmetricDifferenceBy,symmetricDifferenceWith,tail,take,takeRight,takeRightWhile,takeWhile,throttle,timeTaken,times,toCamelCase,toCurrency,toDecimalMark,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toggleClass,tomorrow,transform,truncateString,truthCheckCollection,unary,uncurry,unescapeHTML,unflattenObject,unfold,union,unionBy,unionWith,uniqueElements,untildify,unzip,unzipWith,validateNumber,without,words,xProd,yesNo,zip,zipObject,zipWith,}
return imports;

2
dist/_30s.min.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -19,7 +19,7 @@
},
"name": "30-seconds-of-code",
"description": "A collection of useful JavaScript snippets.",
"version": "0.0.1",
"version": "0.0.2",
"main": "dist/_30s.js",
"module": "dist/_30s.esm.js",
"scripts": {

View File

@ -10,5 +10,5 @@ const functionName = arguments =>
```
```js
functionName('sampleInput') // 'sampleOutput'
functionName('sampleInput'); // 'sampleOutput'
```

15
snippets/all.md Normal file
View File

@ -0,0 +1,15 @@
### 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.
```js
const all = (arr, fn = Boolean) => arr.every(fn);
```
```js
all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true
```

15
snippets/any.md Normal file
View File

@ -0,0 +1,15 @@
### 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.
```js
const any = (arr, fn = Boolean) => arr.some(fn);
```
```js
any([0, 1, 2, 0], x => x >= 2); // true
any([0, 0, 1, 0]); // true
```

View File

@ -0,0 +1,14 @@
### 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`.
```js
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
```
```js
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
```

14
snippets/bifurcate.md Normal file
View File

@ -0,0 +1,14 @@
### bifurcate
Splits values into two groups. If an element in `filter` is truthy, the corresponding element in the collection belongs to the first group; otherwise, it belongs to the second group.
Use `Array.reduce()` and `Array.push()` to add elements to groups, based on `filter`.
```js
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
```
```js
bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]
```

14
snippets/bifurcateBy.md Normal file
View File

@ -0,0 +1,14 @@
### bifurcateBy
Splits values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to. If the predicate function returns a truthy value, the collection element belongs to the first group; otherwise, it belongs to the second group.
Use `Array.reduce()` and `Array.push()` to add elements to groups, based on the value returned by `fn` for each element.
```js
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
```
```js
bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]
```

View File

@ -0,0 +1,26 @@
### binomialCoefficient
Evaluates the binomial coefficient of two integers `n` and `k`.
Use `Number.isNaN()` to check if any of the two values is `NaN`.
Check if `k` is less than `0`, greater than or equal to `n`, equal to `1` or `n - 1` and return the appropriate result.
Check if `n - k` is less than `k` and switch their values accordingly.
Loop from `2` through `k` and calculate the binomial coefficient.
Use `Math.round()` to account for rounding errors in the calculation.
```js
const binomialCoefficient = (n, k) => {
if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
if (k < 0 || k > n) return 0;
if (k === 0 || k === n) return 1;
if (k === 1 || k === n - 1) return n;
if (n - k < k) k = n - k;
let res = n;
for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
return Math.round(res);
};
```
```js
binomialCoefficient(8, 2); // 28
```

13
snippets/degreesToRads.md Normal file
View File

@ -0,0 +1,13 @@
### degreesToRads
Converts an angle from degrees to radians.
Use `Math.PI` and the degree to radian formula to convert the angle from degrees to radians.
```js
const degreesToRads = deg => deg * Math.PI / 180.0;
```
```js
degreesToRads(90.0); // ~1.5708
```

View File

@ -0,0 +1,31 @@
### mostPerformant
Returns the index of the function in an array of functions which executed the fastest.
Use `Array.map()` to generate an array where each value is the total time taken to execute the function after `iterations` times. Use the difference in `performance.now()` values before and after to get the total time in milliseconds to a high degree of accuracy.
Use `Math.min()` to find the minimum execution time, and return the index of that shortest time which corresponds to the index of the most performant function.
Omit the second argument, `iterations`, to use a default of 10,000 iterations. The more iterations, the more reliable the result but the longer it will take.
```js
const mostPerformant = (fns, iterations = 10000) => {
const times = fns.map(fn => {
const before = performance.now();
for (let i = 0; i < iterations; i++) fn();
return performance.now() - before;
});
return times.indexOf(Math.min(...times));
};
```
```js
mostPerformant([
() => {
// Loops through the entire array before returning `false`
[1, 2, 3, 4, 5, 6, 7, 8, 9, '10'].every(el => typeof el === 'number');
},
() => {
// Only needs to reach index `1` before returning false
[1, '2', 3, 4, 5, 6, 7, 8, 9, 10].every(el => typeof el === 'number');
}
]); // 1
```

15
snippets/none.md Normal file
View File

@ -0,0 +1,15 @@
### none
Returns `true` if the provided predicate function returns `false` for all elements 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.
```js
const none = (arr, fn = Boolean) => !arr.some(fn);
```
```js
none([0, 1, 3, 0], x => x == 2); // true
none([0, 0, 0]); // true
```

13
snippets/radsToDegrees.md Normal file
View File

@ -0,0 +1,13 @@
### radsToDegrees
Converts an angle from radians to degrees.
Use `Math.PI` and the radian to degree formula to convert the angle from radians to degrees.
```js
const radsToDegrees = rad => rad * 180.0 / Math.PI;
```
```js
radsToDegrees(Math.PI / 2); // 90
```

21
snippets/stableSort.md Normal file
View File

@ -0,0 +1,21 @@
### stableSort
Performs stable sorting of an array, preserving the initial indexes of items when their values are the same.
Does not mutate the original array, but returns a new array instead.
Use `Array.map()` to pair each element of the input array with its corresponding index.
Use `Array.sort()` and a `compare` function to sort the list, preserving their initial order if the items compared are equal.
Use `Array.map()` to convert back to the initial array items.
```js
const stableSort = (arr, compare) =>
arr
.map((item, index) => ({ item, index }))
.sort((a, b) => compare(a.item, b.item) || a.index - b.index)
.map(({ item }) => item);
```
```js
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const stable = stableSort(arr, () => 0); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
```

23
snippets/uncurry.md Normal file
View File

@ -0,0 +1,23 @@
### uncurry
Uncurries a function up to depth `n`.
Return a variadic function.
Use `Array.reduce()` on the provided arguments to call each subsequent curry level of the function.
If the `length` of the provided arguments is less than `n` throw an error.
Otherwise, call `fn` with the proper amount of arguments, using `Array.slice(0, n)`.
Omit the second argument, `n`, to uncurry up to depth `1`.
```js
const uncurry = (fn, n = 1) => (...args) => {
const next = acc => args => args.reduce((x, y) => x(y), acc);
if (n > args.length) throw new RangeError('Arguments too few!');
return next(fn)(args.slice(0, n));
};
```
```js
const add = x => y => z => x + y + z;
const uncurriedAdd = uncurry(add, 3);
uncurriedAdd(1, 2, 3); // 6
```

View File

@ -1,12 +1,18 @@
all:array,function
any:array,function
approximatelyEqual:math
arrayToHtmlList:browser,array
ary:adapter,function
atob:node,string,utility
attempt:function
average:math,array
averageBy:math,array,function
bifurcate:array
bifurcateBy:array,function
bind:function,object
bindAll:object,function
bindKey:function,object
binomialCoefficient:math
bottomVisible:browser
btoa:node,string,utility
byteSize:string
@ -39,6 +45,7 @@ deepClone:object,recursion
deepFlatten:array,recursion
defaults:object
defer:function
degreesToRads:math
delay:function
detectDeviceType:browser
difference:array,math
@ -153,7 +160,9 @@ memoize:function
merge:object,array
minBy:math,array,function
minN:array,math
mostPerformant:utility,function
negate:function
none:array,function
nthArg:utility,function
nthElement:array
objectFromPairs:object,array
@ -188,6 +197,7 @@ pull:array
pullAtIndex:array
pullAtValue:array
pullBy:array,function,advanced
radsToDegrees:math
randomHexColorCode:utility,random
randomIntArrayInRange:math,utility,random
randomIntegerInRange:math,utility,random
@ -224,6 +234,7 @@ sortedLastIndex:array,math
sortedLastIndexBy:array,math,function
splitLines:string
spreadOver:adapter
stableSort:array,sort,advanced
standardDeviation:math,array
stringPermutations:string,recursion
stripHTMLTags:string,utility,regexp
@ -254,6 +265,7 @@ transform:object,array
truncateString:string
truthCheckCollection:object,logic,array
unary:adapter,function
uncurry:function
unescapeHTML:string,browser
unflattenObject:object,advanced
unfold:function,array

2
test/all/all.js Normal file
View File

@ -0,0 +1,2 @@
const all = (arr, fn = Boolean) => arr.every(fn);
module.exports = all;

21
test/all/all.test.js Normal file
View File

@ -0,0 +1,21 @@
const test = require('tape');
const all = require('./all.js');
test('Testing all', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof all === 'function', 'all is a Function');
t.true(all([4,1,2,3]), 'Returns true for arrays with no falsey values');
t.false(all([0,1]), 'Returns false for arrays with 0');
t.false(all([NaN,1]), 'Returns false for arrays with NaN');
t.false(all([undefined,1]), 'Returns false for arrays with undefined');
t.false(all([null,1]), 'Returns false for arrays with null');
t.false(all(['',1]), 'Returns false for arrays with empty strings');
t.true(all([4,1,2,3], x => x >= 1), 'Returns true with predicate function');
t.false(all([0,1], x => x >= 1), 'Returns false with a predicate function');
//t.deepEqual(all(args..), 'Expected');
//t.equal(all(args..), 'Expected');
//t.false(all(args..), 'Expected');
//t.throws(all(args..), 'Expected');
t.end();
});

2
test/any/any.js Normal file
View File

@ -0,0 +1,2 @@
const any = (arr, fn = Boolean) => arr.some(fn);
module.exports = any;

18
test/any/any.test.js Normal file
View File

@ -0,0 +1,18 @@
const test = require('tape');
const any = require('./any.js');
test('Testing any', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof any === 'function', 'any is a Function');
t.true(any([0,1,2,3]), 'Returns true for arrays with at least one truthy value');
t.false(any([0,0]), 'Returns false for arrays with no truthy values');
t.false(any([NaN,0,undefined,null,'']), 'Returns false for arrays with no truthy values');
t.true(any([4,1,0,3], x => x >= 1), 'Returns true with predicate function');
t.false(any([0,1], x => x < 0), 'Returns false with a predicate function');
//t.deepEqual(any(args..), 'Expected');
//t.equal(any(args..), 'Expected');
//t.false(any(args..), 'Expected');
//t.throws(any(args..), 'Expected');
t.end();
});

View File

@ -0,0 +1,2 @@
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
module.exports = approximatelyEqual;

View File

@ -0,0 +1,17 @@
const test = require('tape');
const approximatelyEqual = require('./approximatelyEqual.js');
test('Testing approximatelyEqual', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof approximatelyEqual === 'function', 'approximatelyEqual is a Function');
t.true(approximatelyEqual(Math.PI / 2.0 , 1.5708), 'Works for PI / 2');
t.true(approximatelyEqual(0.1 + 0.2, 0.3), 'Works for 0.1 + 0.2 === 0.3');
t.true(approximatelyEqual(0.5, 0.5), 'Works for exactly equal values');
t.true(approximatelyEqual(0.501, 0.5, 0.1), 'Works for a custom epsilon');
//t.deepEqual(approximatelyEqual(args..), 'Expected');
//t.equal(approximatelyEqual(args..), 'Expected');
//t.false(approximatelyEqual(args..), 'Expected');
//t.throws(approximatelyEqual(args..), 'Expected');
t.end();
});

View File

@ -5,9 +5,10 @@ test('Testing arrayToHtmlList', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof arrayToHtmlList === 'function', 'arrayToHtmlList is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(arrayToHtmlList(args..), 'Expected');
//t.equal(arrayToHtmlList(args..), 'Expected');
//t.false(arrayToHtmlList(args..), 'Expected');
//t.throws(arrayToHtmlList(args..), 'Expected');
t.end();
});
});

View File

@ -19,6 +19,6 @@ test('Testing average', (t) => {
let start = new Date().getTime();
average(153, 44, 55, 64, 71, 1122, 322774, 2232, 23423, 234, 3631);
let end = new Date().getTime();
t.true((end - start) < 2000, 'head([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]) takes less than 2s to run');
t.true((end - start) < 2000, 'average([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 1122, 32124, 23232]) takes less than 2s to run');
t.end();
});

View File

@ -0,0 +1,3 @@
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
module.exports = bifurcate;

View File

@ -0,0 +1,14 @@
const test = require('tape');
const bifurcate = require('./bifurcate.js');
test('Testing bifurcate', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof bifurcate === 'function', 'bifurcate is a Function');
t.deepEqual(bifurcate([ 'beep', 'boop', 'foo', 'bar' ], [ true, true, false, true ]), [ ['beep', 'boop', 'bar'], ['foo'] ], 'Splits the collection into two groups');
//t.deepEqual(bifurcate(args..), 'Expected');
//t.equal(bifurcate(args..), 'Expected');
//t.false(bifurcate(args..), 'Expected');
//t.throws(bifurcate(args..), 'Expected');
t.end();
});

View File

@ -0,0 +1,3 @@
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
module.exports = bifurcateBy;

View File

@ -0,0 +1,14 @@
const test = require('tape');
const bifurcateBy = require('./bifurcateBy.js');
test('Testing bifurcateBy', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof bifurcateBy === 'function', 'bifurcateBy is a Function');
t.deepEqual(bifurcateBy([ 'beep', 'boop', 'foo', 'bar' ], x => x[0] === 'b'), [ ['beep', 'boop', 'bar'], ['foo'] ], 'Splits the collection into two groups');
//t.deepEqual(bifurcateBy(args..), 'Expected');
//t.equal(bifurcateBy(args..), 'Expected');
//t.false(bifurcateBy(args..), 'Expected');
//t.throws(bifurcateBy(args..), 'Expected');
t.end();
});

View File

@ -0,0 +1,11 @@
const binomialCoefficient = (n, k) => {
if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
if (k < 0 || k > n) return 0;
if (k === 0 || k === n) return 1;
if (k === 1 || k === n - 1) return n;
if (n - k < k) k = n - k;
let res = n;
for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
return Math.round(res);
};
module.exports = binomialCoefficient;

View File

@ -0,0 +1,18 @@
const test = require('tape');
const binomialCoefficient = require('./binomialCoefficient.js');
test('Testing binomialCoefficient', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof binomialCoefficient === 'function', 'binomialCoefficient is a Function');
t.equal(binomialCoefficient(8, 2), 28, 'Returns the appropriate value');
t.equal(binomialCoefficient(0, 0), 1, 'Returns the appropriate value');
t.equal(binomialCoefficient(5, 3), 10, 'Returns the appropriate value');
t.true(Number.isNaN(binomialCoefficient(NaN, 3)), 'Returns NaN');
t.true(Number.isNaN(binomialCoefficient(5, NaN)), 'Returns NaN');
//t.deepEqual(binomialCoefficient(args..), 'Expected');
//t.equal(binomialCoefficient(args..), 'Expected');
//t.false(binomialCoefficient(args..), 'Expected');
//t.throws(binomialCoefficient(args..), 'Expected');
t.end();
});

View File

@ -5,22 +5,19 @@ test('Testing chainAsync', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof chainAsync === 'function', 'chainAsync is a Function');
//t.deepEqual(chainAsync(args..), 'Expected');
// chainAsync([
// next => {
// next();
// },
// next => {
// (() =>{
// next()
// })();
// },
// next => {
// t.pass("Calls all functions in an array");
// next();
// }
// ]);
//
chainAsync([
next => {
next();
},
next => {
(() => {
next();
})();
},
next => {
t.pass("Calls all functions in an array");
}
]);
// // Ensure we wait for the 2nd assertion to be made
// t.plan(2);

View File

@ -5,9 +5,10 @@ test('Testing createElement', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof createElement === 'function', 'createElement is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(createElement(args..), 'Expected');
//t.equal(createElement(args..), 'Expected');
//t.false(createElement(args..), 'Expected');
//t.throws(createElement(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing createEventHub', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof createEventHub === 'function', 'createEventHub is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(createEventHub(args..), 'Expected');
//t.equal(createEventHub(args..), 'Expected');
//t.false(createEventHub(args..), 'Expected');
//t.throws(createEventHub(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing currentURL', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof currentURL === 'function', 'currentURL is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(currentURL(args..), 'Expected');
//t.equal(currentURL(args..), 'Expected');
//t.false(currentURL(args..), 'Expected');
//t.throws(currentURL(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing debounce', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof debounce === 'function', 'debounce is a Function');
debounce(() => {t.pass('Works as expected');}, 250);
//t.deepEqual(debounce(args..), 'Expected');
//t.equal(debounce(args..), 'Expected');
//t.false(debounce(args..), 'Expected');
//t.throws(debounce(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing defaults', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof defaults === 'function', 'defaults is a Function');
t.deepEqual(defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }), { a: 1, b: 2 }, 'Assigns default values for undefined properties');
//t.deepEqual(defaults(args..), 'Expected');
//t.equal(defaults(args..), 'Expected');
//t.false(defaults(args..), 'Expected');
//t.throws(defaults(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing defer', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof defer === 'function', 'defer is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(defer(args..), 'Expected');
//t.equal(defer(args..), 'Expected');
//t.false(defer(args..), 'Expected');
//t.throws(defer(args..), 'Expected');
t.end();
});
});

View File

@ -0,0 +1,2 @@
const degreesToRads = deg => deg * Math.PI / 180.0;
module.exports = degreesToRads;

View File

@ -0,0 +1,15 @@
const test = require('tape');
const degreesToRads = require('./degreesToRads.js');
test('Testing degreesToRads', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
const approxeq = (v1,v2, diff = 0.001) => Math.abs(v1 - v2) < diff; // Use to account for rounding errors
t.true(typeof degreesToRads === 'function', 'degreesToRads is a Function');
t.true(approxeq(degreesToRads(90.0), Math.PI / 2), 'Returns the appropriate value');
//t.deepEqual(degreesToRads(args..), 'Expected');
//t.equal(degreesToRads(args..), 'Expected');
//t.false(degreesToRads(args..), 'Expected');
//t.throws(degreesToRads(args..), 'Expected');
t.end();
});

View File

@ -5,9 +5,16 @@ test('Testing delay', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof delay === 'function', 'delay is a Function');
delay(
function(text) {
t.equals(text, 'test', 'Works as expecting, passing arguments properly');
},
1000,
'test'
);
//t.deepEqual(delay(args..), 'Expected');
//t.equal(delay(args..), 'Expected');
//t.false(delay(args..), 'Expected');
//t.throws(delay(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing getScrollPosition', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof getScrollPosition === 'function', 'getScrollPosition is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(getScrollPosition(args..), 'Expected');
//t.equal(getScrollPosition(args..), 'Expected');
//t.false(getScrollPosition(args..), 'Expected');
//t.throws(getScrollPosition(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing getStyle', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof getStyle === 'function', 'getStyle is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(getStyle(args..), 'Expected');
//t.equal(getStyle(args..), 'Expected');
//t.false(getStyle(args..), 'Expected');
//t.throws(getStyle(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing hasFlags', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof hasFlags === 'function', 'hasFlags is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(hasFlags(args..), 'Expected');
//t.equal(hasFlags(args..), 'Expected');
//t.false(hasFlags(args..), 'Expected');
//t.throws(hasFlags(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing hashBrowser', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof hashBrowser === 'function', 'hashBrowser is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(hashBrowser(args..), 'Expected');
//t.equal(hashBrowser(args..), 'Expected');
//t.false(hashBrowser(args..), 'Expected');
//t.throws(hashBrowser(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing hide', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof hide === 'function', 'hide is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(hide(args..), 'Expected');
//t.equal(hide(args..), 'Expected');
//t.false(hide(args..), 'Expected');
//t.throws(hide(args..), 'Expected');
t.end();
});
});

View File

@ -0,0 +1,9 @@
const mostPerformant = (fns, iterations = 10000) => {
const times = fns.map(fn => {
const before = performance.now();
for (let i = 0; i < iterations; i++) fn();
return performance.now() - before;
});
return times.indexOf(Math.min(...times));
};
module.exports = mostPerformant;

View File

@ -0,0 +1,14 @@
const test = require('tape');
const mostPerformant = require('./mostPerformant.js');
test('Testing mostPerformant', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof mostPerformant === 'function', 'mostPerformant is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(mostPerformant(args..), 'Expected');
//t.equal(mostPerformant(args..), 'Expected');
//t.false(mostPerformant(args..), 'Expected');
//t.throws(mostPerformant(args..), 'Expected');
t.end();
});

2
test/none/none.js Normal file
View File

@ -0,0 +1,2 @@
const none = (arr, fn = Boolean) => !arr.some(fn);
module.exports = none;

17
test/none/none.test.js Normal file
View File

@ -0,0 +1,17 @@
const test = require('tape');
const none = require('./none.js');
test('Testing none', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof none === 'function', 'none is a Function');
t.true(none([0,undefined,NaN,null,'']), 'Returns true for arrays with no truthy values');
t.false(none([0,1]), 'Returns false for arrays with at least one truthy value');
t.true(none([4,1,0,3], x => x < 0), 'Returns true with a predicate function');
t.false(none([0,1,2], x => x === 1), 'Returns false with predicate function');
//t.deepEqual(none(args..), 'Expected');
//t.equal(none(args..), 'Expected');
//t.false(none(args..), 'Expected');
//t.throws(none(args..), 'Expected');
t.end();
});

View File

@ -5,9 +5,10 @@ test('Testing off', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof off === 'function', 'off is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(off(args..), 'Expected');
//t.equal(off(args..), 'Expected');
//t.false(off(args..), 'Expected');
//t.throws(off(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing on', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof on === 'function', 'on is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(on(args..), 'Expected');
//t.equal(on(args..), 'Expected');
//t.false(on(args..), 'Expected');
//t.throws(on(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing onUserInputChange', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof onUserInputChange === 'function', 'onUserInputChange is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(onUserInputChange(args..), 'Expected');
//t.equal(onUserInputChange(args..), 'Expected');
//t.false(onUserInputChange(args..), 'Expected');
//t.throws(onUserInputChange(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing once', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof once === 'function', 'once is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(once(args..), 'Expected');
//t.equal(once(args..), 'Expected');
//t.false(once(args..), 'Expected');
//t.throws(once(args..), 'Expected');
t.end();
});
});

View File

@ -0,0 +1,2 @@
const radsToDegrees = rad => rad * 180.0 / Math.PI;
module.exports = radsToDegrees;

View File

@ -0,0 +1,14 @@
const test = require('tape');
const radsToDegrees = require('./radsToDegrees.js');
test('Testing radsToDegrees', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof radsToDegrees === 'function', 'radsToDegrees is a Function');
t.equal(radsToDegrees(Math.PI / 2), 90, 'Returns the appropriate value');
//t.deepEqual(radsToDegrees(args..), 'Expected');
//t.equal(radsToDegrees(args..), 'Expected');
//t.false(radsToDegrees(args..), 'Expected');
//t.throws(radsToDegrees(args..), 'Expected');
t.end();
});

View File

@ -7,7 +7,9 @@ test('Testing randomHexColorCode', (t) => {
t.true(typeof randomHexColorCode === 'function', 'randomHexColorCode is a Function');
//t.deepEqual(randomHexColorCode(args..), 'Expected');
t.equal(randomHexColorCode().length, 7);
t.true(randomHexColorCode().startsWith('#'),'The color code starts with "#"');
t.true(randomHexColorCode().slice(1).match(/[^0123456789abcdef]/i) === null,'The color code contains only valid hex-digits');
//t.false(randomHexColorCode(args..), 'Expected');
//t.throws(randomHexColorCode(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing setStyle', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof setStyle === 'function', 'setStyle is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(setStyle(args..), 'Expected');
//t.equal(setStyle(args..), 'Expected');
//t.false(setStyle(args..), 'Expected');
//t.throws(setStyle(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing show', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof show === 'function', 'show is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(show(args..), 'Expected');
//t.equal(show(args..), 'Expected');
//t.false(show(args..), 'Expected');
//t.throws(show(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,13 @@ test('Testing sleep', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof sleep === 'function', 'sleep is a Function');
async function sleepyWork() {
await sleep(1000);
t.pass('Works as expected');
}
//t.deepEqual(sleep(args..), 'Expected');
//t.equal(sleep(args..), 'Expected');
//t.false(sleep(args..), 'Expected');
//t.throws(sleep(args..), 'Expected');
t.end();
});
});

View File

@ -0,0 +1,6 @@
const stableSort = (arr, compare) =>
arr
.map((item, index) => ({ item, index }))
.sort((a, b) => compare(a.item, b.item) || a.index - b.index)
.map(({ item }) => item);
module.exports = stableSort;

View File

@ -0,0 +1,17 @@
const test = require('tape');
const stableSort = require('./stableSort.js');
test('Testing stableSort', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof stableSort === 'function', 'stableSort is a Function');
//t.deepEqual(stableSort(args..), 'Expected');
//t.equal(stableSort(args..), 'Expected');
//t.false(stableSort(args..), 'Expected');
//t.throws(stableSort(args..), 'Expected');
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const compare = () => 0;
t.deepEqual(stableSort(arr, compare), arr, 'Array is properly sorted');
t.end();
});

View File

@ -5,9 +5,10 @@ test('Testing throttle', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof throttle === 'function', 'throttle is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(throttle(args..), 'Expected');
//t.equal(throttle(args..), 'Expected');
//t.false(throttle(args..), 'Expected');
//t.throws(throttle(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing timeTaken', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof timeTaken === 'function', 'timeTaken is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(timeTaken(args..), 'Expected');
//t.equal(timeTaken(args..), 'Expected');
//t.false(timeTaken(args..), 'Expected');
//t.throws(timeTaken(args..), 'Expected');
t.end();
});
});

View File

@ -5,9 +5,10 @@ test('Testing toggleClass', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof toggleClass === 'function', 'toggleClass is a Function');
t.pass('Tested by @chalarangelo on 16/02/2018');
//t.deepEqual(toggleClass(args..), 'Expected');
//t.equal(toggleClass(args..), 'Expected');
//t.false(toggleClass(args..), 'Expected');
//t.throws(toggleClass(args..), 'Expected');
t.end();
});
});

6
test/uncurry/uncurry.js Normal file
View File

@ -0,0 +1,6 @@
const uncurry = (fn, n = 1) => (...args) => {
const next = acc => args => args.reduce((x, y) => x(y), acc);
if (n > args.length) throw new RangeError('Arguments too few!');
return next(fn)(args.slice(0, n));
};
module.exports = uncurry;

View File

@ -0,0 +1,20 @@
const test = require('tape');
const uncurry = require('./uncurry.js');
test('Testing uncurry', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof uncurry === 'function', 'uncurry is a Function');
const add = x => y => z => x + y + z;
const add1 = uncurry(add);
const add2 = uncurry(add, 2);
const add3 = uncurry(add, 3);
t.equal(add1(1)(2)(3), 6, 'Works without a provided value for n');
t.equal(add2(1,2)(3), 6, 'Works without n = 2');
t.equal(add3(1,2,3), 6, 'Works withoutn = 3');
//t.deepEqual(uncurry(args..), 'Expected');
//t.equal(uncurry(args..), 'Expected');
//t.false(uncurry(args..), 'Expected');
//t.throws(uncurry(args..), 'Expected');
t.end();
});