Merge branch 'add-toCurrency' of https://github.com/Chalarangelo/30-seconds-of-code into add-toCurrency
This commit is contained in:
@ -38,14 +38,17 @@ Here's what you can do to help:
|
||||
- You can start creating a new snippet, by using the [snippet template](snippet-template.md) to format your snippets.
|
||||
|
||||
### Writing tests
|
||||
- Before writing any tests run `npm run tdd` script. It will update test directory to include new snippets as well as update old ones if needed.
|
||||
- Before writing any tests run `npm run tester` script. It will update test directory to include new snippets as well as update old ones if needed.
|
||||
- **DO NOT MODIFY THE snippetName.js files** under test directory.
|
||||
- We are using [tape](https://github.com/substack/tape) for testing.
|
||||
- Write tests under `snippetName.test.js` file. If you have trouble doing so, check out tests of other snippets.
|
||||
- Be sure to run `npm run test`. It is going to run all tests for all snippets.
|
||||
- Make a new pull request **only if all the tests are passing**.
|
||||
|
||||
|
||||
#### Browser specific tests
|
||||
- If your snippet belongs to `browser` category, then you will need to modify the tests to make them work.
|
||||
- By default, `Node.js` isn't browser environment. That said we have to use an external package to help us simulate the browser for our tests.
|
||||
- We use [jsdom](https://www.npmjs.com/package/jsdom) for our browser specific tests. You can find their [documentation](https://github.com/jsdom/jsdom) on GitHub as well.
|
||||
|
||||
### Additional guidelines and conventions regarding snippets
|
||||
|
||||
|
||||
229
README.md
229
README.md
@ -82,8 +82,11 @@ average(1, 2, 3);
|
||||
* [`collectInto`](#collectinto)
|
||||
* [`flip`](#flip)
|
||||
* [`over`](#over)
|
||||
* [`overArgs`](#overargs)
|
||||
* [`pipeAsyncFunctions`](#pipeasyncfunctions)
|
||||
* [`pipeFunctions`](#pipefunctions)
|
||||
* [`promisify`](#promisify)
|
||||
* [`rearg`](#rearg)
|
||||
* [`spreadOver`](#spreadover)
|
||||
* [`unary`](#unary)
|
||||
|
||||
@ -219,12 +222,14 @@ average(1, 2, 3);
|
||||
<details>
|
||||
<summary>View contents</summary>
|
||||
|
||||
* [`attempt`](#attempt)
|
||||
* [`bind`](#bind)
|
||||
* [`bindKey`](#bindkey)
|
||||
* [`chainAsync`](#chainasync)
|
||||
* [`compose`](#compose)
|
||||
* [`composeRight`](#composeright)
|
||||
* [`curry`](#curry)
|
||||
* [`debounce`](#debounce)
|
||||
* [`defer`](#defer)
|
||||
* [`delay`](#delay)
|
||||
* [`functionName`](#functionname)
|
||||
@ -235,6 +240,7 @@ average(1, 2, 3);
|
||||
* [`partialRight`](#partialright)
|
||||
* [`runPromisesInSeries`](#runpromisesinseries)
|
||||
* [`sleep`](#sleep)
|
||||
* [`throttle`](#throttle)
|
||||
* [`times`](#times)
|
||||
* [`unfold`](#unfold)
|
||||
|
||||
@ -495,7 +501,7 @@ const Pall = collectInto(Promise.all.bind(Promise));
|
||||
let p1 = Promise.resolve(1);
|
||||
let p2 = Promise.resolve(2);
|
||||
let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
|
||||
Pall(p1, p2, p3).then(console.log);
|
||||
Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)
|
||||
```
|
||||
|
||||
</details>
|
||||
@ -554,6 +560,66 @@ minMax(1, 2, 3, 4, 5); // [1,5]
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### overArgs
|
||||
|
||||
Creates a function that invokes the provided function with its arguments transformed.
|
||||
|
||||
Use `Array.map()` to apply `transforms` to `args` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.
|
||||
|
||||
```js
|
||||
const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
var func = overArgs(
|
||||
function(x, y) {
|
||||
return [x, y];
|
||||
},
|
||||
[square, doubled]
|
||||
);
|
||||
func(9, 3); // [81, 6]
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### pipeAsyncFunctions
|
||||
|
||||
Performs left-to-right function composition for asynchronous functions.
|
||||
|
||||
Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition using `Promise.then()`.
|
||||
The functions can return a combination of: simple values, `Promise`'s, or they can be defined as `async` ones returning through `await`.
|
||||
All functions must be unary.
|
||||
|
||||
```js
|
||||
const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
const sum = pipeAsyncFunctions(
|
||||
x => x + 1,
|
||||
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
|
||||
x => x + 3,
|
||||
async x => (await x) + 4
|
||||
);
|
||||
(async () => {
|
||||
console.log(await sum(5)); // 15 (after one second)
|
||||
})();
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### pipeFunctions
|
||||
|
||||
Performs left-to-right function composition.
|
||||
@ -609,6 +675,40 @@ delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### rearg
|
||||
|
||||
Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.
|
||||
|
||||
Use `Array.reduce()` and `Array.indexOf()` to reorder arguments based on `indexes` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.
|
||||
|
||||
```js
|
||||
const rearg = (fn, indexes) => (...args) =>
|
||||
fn(
|
||||
...args.reduce(
|
||||
(acc, val, i) => ((acc[indexes.indexOf(i)] = val), acc),
|
||||
Array.from({ length: indexes.length })
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
var rearged = rearg(
|
||||
function(a, b, c) {
|
||||
return [a, b, c];
|
||||
},
|
||||
[2, 0, 1]
|
||||
);
|
||||
rearged('b', 'c', 'a'); // ['a', 'b', 'c']
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### spreadOver
|
||||
|
||||
Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.
|
||||
@ -3432,6 +3532,37 @@ tomorrow(); // 2017-12-27 (if current date is 2017-12-26)
|
||||
---
|
||||
## 🎛️ 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.
|
||||
|
||||
```js
|
||||
const attempt = (fn, ...args) => {
|
||||
try {
|
||||
return fn(args);
|
||||
} catch (e) {
|
||||
return e instanceof Error ? e : new Error(e);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
var elements = attempt(function(selector) {
|
||||
return document.querySelectorAll(selector);
|
||||
}, '>_>');
|
||||
if (elements instanceof Error) elements = []; // elements = []
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### bind
|
||||
|
||||
Creates a function that invokes `fn` with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.
|
||||
@ -3609,6 +3740,44 @@ curry(Math.min, 3)(10)(50)(2); // 2
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### debounce
|
||||
|
||||
Creates a debounced function that delays invoking the provided function until after `wait` milliseconds have elapsed since the last time the debounced function was invoked.
|
||||
|
||||
Use `setTimeout()` and `clearTimeout()` to debounce the given method, `fn`.
|
||||
Use `Function.apply()` to apply the `this` context to the function and provide the necessary `arguments`.
|
||||
Omit the second argument, `wait`, to set the timeout at a default of 0 ms.
|
||||
|
||||
```js
|
||||
const debounce = (fn, wait = 0) => {
|
||||
let inDebounce;
|
||||
return function() {
|
||||
const context = this,
|
||||
args = arguments;
|
||||
clearTimeout(inDebounce);
|
||||
inDebounce = setTimeout(() => fn.apply(context, args), wait);
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
window.addEventListener(
|
||||
'resize',
|
||||
debounce(function(evt) {
|
||||
console.log(window.innerWidth);
|
||||
console.log(window.innerHeight);
|
||||
}, 250)
|
||||
); // Will log the window dimensions at most every 250ms
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### defer
|
||||
|
||||
Defers invoking a function until the current call stack has cleared.
|
||||
@ -3879,6 +4048,56 @@ async function sleepyWork() {
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### throttle
|
||||
|
||||
Creates a throttled function that only invokes the provided function at most once per every `wait` milliseconds
|
||||
|
||||
Use `setTimeout()` and `clearTimeout()` to throttle the given method, `fn`.
|
||||
Use `Function.apply()` to apply the `this` context to the function and provide the necessary `arguments`.
|
||||
Use `Date.now()` to keep track of the last time the throttled function was invoked.
|
||||
Omit the second argument, `wait`, to set the timeout at a default of 0 ms.
|
||||
|
||||
```js
|
||||
const throttle = (fn, wait) => {
|
||||
let inThrottle, lastFn, lastTime;
|
||||
return function() {
|
||||
const context = this,
|
||||
args = arguments;
|
||||
if (!inThrottle) {
|
||||
fn.apply(context, args);
|
||||
lastTime = Date.now();
|
||||
inThrottle = true;
|
||||
} else {
|
||||
clearTimeout(lastFn);
|
||||
lastFn = setTimeout(function() {
|
||||
if (Date.now() - lastTime >= wait) {
|
||||
fn.apply(context, args);
|
||||
lastTime = Date.now();
|
||||
}
|
||||
}, wait - (Date.now() - lastTime));
|
||||
}
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
window.addEventListener(
|
||||
'resize',
|
||||
throttle(function(evt) {
|
||||
console.log(window.innerWidth);
|
||||
console.log(window.innerHeight);
|
||||
}, 250)
|
||||
); // Will log the window dimensions at most every 250ms
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### times
|
||||
|
||||
Iterates over a callback `n` times
|
||||
@ -5095,17 +5314,17 @@ UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'
|
||||
|
||||
### bindAll
|
||||
|
||||
Explain briefly what the snippet does.
|
||||
|
||||
Use `Array.forEach()` to return a `function` that uses `Function.apply()` to apply the given context (`obj`) to `fn` for each function specified.
|
||||
|
||||
```js
|
||||
const bindAll = (obj, ...fns) =>
|
||||
fns.forEach(
|
||||
fn =>
|
||||
fn => (
|
||||
(f = obj[fn]),
|
||||
(obj[fn] = function() {
|
||||
return fn.apply(obj);
|
||||
return f.apply(obj);
|
||||
})
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
|
||||
161
dist/_30s.es5.js
vendored
161
dist/_30s.es5.js
vendored
File diff suppressed because one or more lines are too long
2
dist/_30s.es5.min.js
vendored
2
dist/_30s.es5.min.js
vendored
File diff suppressed because one or more lines are too long
59
dist/_30s.esm.js
vendored
59
dist/_30s.esm.js
vendored
@ -43,6 +43,14 @@ const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
|
||||
|
||||
const atob = str => new Buffer(str, 'base64').toString('binary');
|
||||
|
||||
const attempt = (fn, ...args) => {
|
||||
try {
|
||||
return fn(args);
|
||||
} catch (e) {
|
||||
return e instanceof Error ? e : new Error(e);
|
||||
}
|
||||
};
|
||||
|
||||
const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length;
|
||||
|
||||
const averageBy = (arr, fn) =>
|
||||
@ -56,9 +64,9 @@ const bind = (fn, context, ...args) =>
|
||||
|
||||
const bindAll = (obj, ...fns) =>
|
||||
fns.forEach(
|
||||
fn =>
|
||||
(obj[fn] = function() {
|
||||
return fn.apply(obj);
|
||||
fn => (
|
||||
f = obj[fn], obj[fn] = function() {
|
||||
return f.apply(obj);
|
||||
})
|
||||
);
|
||||
|
||||
@ -182,6 +190,16 @@ const currentURL = () => window.location.href;
|
||||
const curry = (fn, arity = fn.length, ...args) =>
|
||||
arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
|
||||
|
||||
const debounce = (fn, wait = 0) => {
|
||||
let inDebounce;
|
||||
return function() {
|
||||
const context = this,
|
||||
args = arguments;
|
||||
clearTimeout(inDebounce);
|
||||
inDebounce = setTimeout(() => fn.apply(context, args), wait);
|
||||
};
|
||||
};
|
||||
|
||||
const decapitalize = ([first, ...rest], upperRest = false) =>
|
||||
first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
|
||||
|
||||
@ -803,6 +821,8 @@ const orderBy = (arr, props, orders) =>
|
||||
|
||||
const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args));
|
||||
|
||||
const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));
|
||||
|
||||
const palindrome = str => {
|
||||
const s = str.toLowerCase().replace(/[\W_]/g, '');
|
||||
return (
|
||||
@ -847,6 +867,8 @@ const pickBy = (obj, fn) =>
|
||||
.filter(k => fn(obj[k], k))
|
||||
.reduce((acc, key) => (acc[key] = obj[key], acc), {});
|
||||
|
||||
const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
|
||||
|
||||
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
|
||||
|
||||
const pluralize = (val, word, plural = word + 's') => {
|
||||
@ -934,6 +956,14 @@ const readFileLines = filename =>
|
||||
.toString('UTF8')
|
||||
.split('\n');
|
||||
|
||||
const rearg = (fn, indexes) => (...args) =>
|
||||
fn(
|
||||
...args.reduce(
|
||||
(acc, val, i) => (acc[indexes.indexOf(i)] = val, acc),
|
||||
Array.from({ length: indexes.length })
|
||||
)
|
||||
);
|
||||
|
||||
const redirect = (url, asLink = true) =>
|
||||
asLink ? (window.location.href = url) : window.location.replace(url);
|
||||
|
||||
@ -1133,6 +1163,27 @@ const takeWhile = (arr, func) => {
|
||||
return arr;
|
||||
};
|
||||
|
||||
const throttle = (fn, wait) => {
|
||||
let inThrottle, lastFn, lastTime;
|
||||
return function() {
|
||||
const context = this,
|
||||
args = arguments;
|
||||
if (!inThrottle) {
|
||||
fn.apply(context, args);
|
||||
lastTime = Date.now();
|
||||
inThrottle = true;
|
||||
} else {
|
||||
clearTimeout(lastFn);
|
||||
lastFn = setTimeout(function() {
|
||||
if (Date.now() - lastTime >= wait) {
|
||||
fn.apply(context, args);
|
||||
lastTime = Date.now();
|
||||
}
|
||||
}, wait - (Date.now() - lastTime));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const timeTaken = callback => {
|
||||
console.time('timeTaken');
|
||||
const r = callback();
|
||||
@ -1288,6 +1339,6 @@ const zipWith = (...arrays) => {
|
||||
return fn ? result.map(arr => fn(...arr)) : result;
|
||||
};
|
||||
|
||||
var imports = {JSONToFile,RGBToHex,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,ary,atob,average,averageBy,bind,bindAll,bindKey,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,composeRight,copyToClipboard,countBy,countOccurrences,createElement,createEventHub,currentURL,curry,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,flip,forEachRight,forOwn,forOwnRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getDaysDiffBetweenDates,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,palindrome,parseCookie,partial,partialRight,partition,percentile,pick,pickBy,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,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,timeTaken,times,toCamelCase,toDecimalMark,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toggleClass,tomorrow,transform,truncateString,truthCheckCollection,unary,unescapeHTML,unfold,union,unionBy,unionWith,uniqueElements,untildify,unzip,unzipWith,validateNumber,without,words,xProd,yesNo,zip,zipObject,zipWith,}
|
||||
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,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,flip,forEachRight,forOwn,forOwnRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getDaysDiffBetweenDates,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,toDecimalMark,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toggleClass,tomorrow,transform,truncateString,truthCheckCollection,unary,unescapeHTML,unfold,union,unionBy,unionWith,uniqueElements,untildify,unzip,unzipWith,validateNumber,without,words,xProd,yesNo,zip,zipObject,zipWith,}
|
||||
|
||||
export default imports;
|
||||
|
||||
59
dist/_30s.js
vendored
59
dist/_30s.js
vendored
@ -49,6 +49,14 @@ const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
|
||||
|
||||
const atob = str => new Buffer(str, 'base64').toString('binary');
|
||||
|
||||
const attempt = (fn, ...args) => {
|
||||
try {
|
||||
return fn(args);
|
||||
} catch (e) {
|
||||
return e instanceof Error ? e : new Error(e);
|
||||
}
|
||||
};
|
||||
|
||||
const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length;
|
||||
|
||||
const averageBy = (arr, fn) =>
|
||||
@ -62,9 +70,9 @@ const bind = (fn, context, ...args) =>
|
||||
|
||||
const bindAll = (obj, ...fns) =>
|
||||
fns.forEach(
|
||||
fn =>
|
||||
(obj[fn] = function() {
|
||||
return fn.apply(obj);
|
||||
fn => (
|
||||
f = obj[fn], obj[fn] = function() {
|
||||
return f.apply(obj);
|
||||
})
|
||||
);
|
||||
|
||||
@ -188,6 +196,16 @@ const currentURL = () => window.location.href;
|
||||
const curry = (fn, arity = fn.length, ...args) =>
|
||||
arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
|
||||
|
||||
const debounce = (fn, wait = 0) => {
|
||||
let inDebounce;
|
||||
return function() {
|
||||
const context = this,
|
||||
args = arguments;
|
||||
clearTimeout(inDebounce);
|
||||
inDebounce = setTimeout(() => fn.apply(context, args), wait);
|
||||
};
|
||||
};
|
||||
|
||||
const decapitalize = ([first, ...rest], upperRest = false) =>
|
||||
first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
|
||||
|
||||
@ -809,6 +827,8 @@ const orderBy = (arr, props, orders) =>
|
||||
|
||||
const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args));
|
||||
|
||||
const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));
|
||||
|
||||
const palindrome = str => {
|
||||
const s = str.toLowerCase().replace(/[\W_]/g, '');
|
||||
return (
|
||||
@ -853,6 +873,8 @@ const pickBy = (obj, fn) =>
|
||||
.filter(k => fn(obj[k], k))
|
||||
.reduce((acc, key) => (acc[key] = obj[key], acc), {});
|
||||
|
||||
const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
|
||||
|
||||
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
|
||||
|
||||
const pluralize = (val, word, plural = word + 's') => {
|
||||
@ -940,6 +962,14 @@ const readFileLines = filename =>
|
||||
.toString('UTF8')
|
||||
.split('\n');
|
||||
|
||||
const rearg = (fn, indexes) => (...args) =>
|
||||
fn(
|
||||
...args.reduce(
|
||||
(acc, val, i) => (acc[indexes.indexOf(i)] = val, acc),
|
||||
Array.from({ length: indexes.length })
|
||||
)
|
||||
);
|
||||
|
||||
const redirect = (url, asLink = true) =>
|
||||
asLink ? (window.location.href = url) : window.location.replace(url);
|
||||
|
||||
@ -1139,6 +1169,27 @@ const takeWhile = (arr, func) => {
|
||||
return arr;
|
||||
};
|
||||
|
||||
const throttle = (fn, wait) => {
|
||||
let inThrottle, lastFn, lastTime;
|
||||
return function() {
|
||||
const context = this,
|
||||
args = arguments;
|
||||
if (!inThrottle) {
|
||||
fn.apply(context, args);
|
||||
lastTime = Date.now();
|
||||
inThrottle = true;
|
||||
} else {
|
||||
clearTimeout(lastFn);
|
||||
lastFn = setTimeout(function() {
|
||||
if (Date.now() - lastTime >= wait) {
|
||||
fn.apply(context, args);
|
||||
lastTime = Date.now();
|
||||
}
|
||||
}, wait - (Date.now() - lastTime));
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const timeTaken = callback => {
|
||||
console.time('timeTaken');
|
||||
const r = callback();
|
||||
@ -1294,7 +1345,7 @@ const zipWith = (...arrays) => {
|
||||
return fn ? result.map(arr => fn(...arr)) : result;
|
||||
};
|
||||
|
||||
var imports = {JSONToFile,RGBToHex,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,ary,atob,average,averageBy,bind,bindAll,bindKey,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,composeRight,copyToClipboard,countBy,countOccurrences,createElement,createEventHub,currentURL,curry,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,flip,forEachRight,forOwn,forOwnRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getDaysDiffBetweenDates,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,palindrome,parseCookie,partial,partialRight,partition,percentile,pick,pickBy,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,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,timeTaken,times,toCamelCase,toDecimalMark,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toggleClass,tomorrow,transform,truncateString,truthCheckCollection,unary,unescapeHTML,unfold,union,unionBy,unionWith,uniqueElements,untildify,unzip,unzipWith,validateNumber,without,words,xProd,yesNo,zip,zipObject,zipWith,}
|
||||
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,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,flip,forEachRight,forOwn,forOwnRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getDaysDiffBetweenDates,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,toDecimalMark,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toggleClass,tomorrow,transform,truncateString,truthCheckCollection,unary,unescapeHTML,unfold,union,unionBy,unionWith,uniqueElements,untildify,unzip,unzipWith,validateNumber,without,words,xProd,yesNo,zip,zipObject,zipWith,}
|
||||
|
||||
return imports;
|
||||
|
||||
|
||||
2
dist/_30s.min.js
vendored
2
dist/_30s.min.js
vendored
File diff suppressed because one or more lines are too long
102
docs/index.html
102
docs/index.html
File diff suppressed because one or more lines are too long
22
snippets/attempt.md
Normal file
22
snippets/attempt.md
Normal file
@ -0,0 +1,22 @@
|
||||
### 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.
|
||||
|
||||
```js
|
||||
const attempt = (fn, ...args) => {
|
||||
try {
|
||||
return fn(args);
|
||||
} catch (e) {
|
||||
return e instanceof Error ? e : new Error(e);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
var elements = attempt(function(selector) {
|
||||
return document.querySelectorAll(selector);
|
||||
}, '>_>');
|
||||
if (elements instanceof Error) elements = []; // elements = []
|
||||
```
|
||||
@ -1,16 +1,16 @@
|
||||
### bindAll
|
||||
|
||||
Explain briefly what the snippet does.
|
||||
|
||||
Use `Array.forEach()` to return a `function` that uses `Function.apply()` to apply the given context (`obj`) to `fn` for each function specified.
|
||||
|
||||
```js
|
||||
const bindAll = (obj, ...fns) =>
|
||||
fns.forEach(
|
||||
fn =>
|
||||
fn => (
|
||||
(f = obj[fn]),
|
||||
(obj[fn] = function() {
|
||||
return fn.apply(obj);
|
||||
return f.apply(obj);
|
||||
})
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
|
||||
@ -13,5 +13,5 @@ const Pall = collectInto(Promise.all.bind(Promise));
|
||||
let p1 = Promise.resolve(1);
|
||||
let p2 = Promise.resolve(2);
|
||||
let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
|
||||
Pall(p1, p2, p3).then(console.log);
|
||||
Pall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)
|
||||
```
|
||||
|
||||
29
snippets/debounce.md
Normal file
29
snippets/debounce.md
Normal file
@ -0,0 +1,29 @@
|
||||
### debounce
|
||||
|
||||
Creates a debounced function that delays invoking the provided function until after `wait` milliseconds have elapsed since the last time the debounced function was invoked.
|
||||
|
||||
Use `setTimeout()` and `clearTimeout()` to debounce the given method, `fn`.
|
||||
Use `Function.apply()` to apply the `this` context to the function and provide the necessary `arguments`.
|
||||
Omit the second argument, `wait`, to set the timeout at a default of 0 ms.
|
||||
|
||||
```js
|
||||
const debounce = (fn, wait = 0) => {
|
||||
let inDebounce;
|
||||
return function() {
|
||||
const context = this,
|
||||
args = arguments;
|
||||
clearTimeout(inDebounce);
|
||||
inDebounce = setTimeout(() => fn.apply(context, args), wait);
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
window.addEventListener(
|
||||
'resize',
|
||||
debounce(function(evt) {
|
||||
console.log(window.innerWidth);
|
||||
console.log(window.innerHeight);
|
||||
}, 250)
|
||||
); // Will log the window dimensions at most every 250ms
|
||||
```
|
||||
19
snippets/overArgs.md
Normal file
19
snippets/overArgs.md
Normal file
@ -0,0 +1,19 @@
|
||||
### overArgs
|
||||
|
||||
Creates a function that invokes the provided function with its arguments transformed.
|
||||
|
||||
Use `Array.map()` to apply `transforms` to `args` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.
|
||||
|
||||
```js
|
||||
const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));
|
||||
```
|
||||
|
||||
```js
|
||||
var func = overArgs(
|
||||
function(x, y) {
|
||||
return [x, y];
|
||||
},
|
||||
[square, doubled]
|
||||
);
|
||||
func(9, 3); // [81, 6]
|
||||
```
|
||||
23
snippets/pipeAsyncFunctions.md
Normal file
23
snippets/pipeAsyncFunctions.md
Normal file
@ -0,0 +1,23 @@
|
||||
### pipeAsyncFunctions
|
||||
|
||||
Performs left-to-right function composition for asynchronous functions.
|
||||
|
||||
Use `Array.reduce()` with the spread operator (`...`) to perform left-to-right function composition using `Promise.then()`.
|
||||
The functions can return a combination of: simple values, `Promise`'s, or they can be defined as `async` ones returning through `await`.
|
||||
All functions must be unary.
|
||||
|
||||
```js
|
||||
const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
|
||||
```
|
||||
|
||||
```js
|
||||
const sum = pipeAsyncFunctions(
|
||||
x => x + 1,
|
||||
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
|
||||
x => x + 3,
|
||||
async x => (await x) + 4
|
||||
);
|
||||
(async () => {
|
||||
console.log(await sum(5)); // 15 (after one second)
|
||||
})();
|
||||
```
|
||||
25
snippets/rearg.md
Normal file
25
snippets/rearg.md
Normal file
@ -0,0 +1,25 @@
|
||||
### rearg
|
||||
|
||||
Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.
|
||||
|
||||
Use `Array.reduce()` and `Array.indexOf()` to reorder arguments based on `indexes` in combination with the spread operator (`...`) to pass the transformed arguments to `fn`.
|
||||
|
||||
```js
|
||||
const rearg = (fn, indexes) => (...args) =>
|
||||
fn(
|
||||
...args.reduce(
|
||||
(acc, val, i) => ((acc[indexes.indexOf(i)] = val), acc),
|
||||
Array.from({ length: indexes.length })
|
||||
)
|
||||
);
|
||||
```
|
||||
|
||||
```js
|
||||
var rearged = rearg(
|
||||
function(a, b, c) {
|
||||
return [a, b, c];
|
||||
},
|
||||
[2, 0, 1]
|
||||
);
|
||||
rearged('b', 'c', 'a'); // ['a', 'b', 'c']
|
||||
```
|
||||
41
snippets/throttle.md
Normal file
41
snippets/throttle.md
Normal file
@ -0,0 +1,41 @@
|
||||
### throttle
|
||||
|
||||
Creates a throttled function that only invokes the provided function at most once per every `wait` milliseconds
|
||||
|
||||
Use `setTimeout()` and `clearTimeout()` to throttle the given method, `fn`.
|
||||
Use `Function.apply()` to apply the `this` context to the function and provide the necessary `arguments`.
|
||||
Use `Date.now()` to keep track of the last time the throttled function was invoked.
|
||||
Omit the second argument, `wait`, to set the timeout at a default of 0 ms.
|
||||
|
||||
```js
|
||||
const throttle = (fn, wait) => {
|
||||
let inThrottle, lastFn, lastTime;
|
||||
return function() {
|
||||
const context = this,
|
||||
args = arguments;
|
||||
if (!inThrottle) {
|
||||
fn.apply(context, args);
|
||||
lastTime = Date.now();
|
||||
inThrottle = true;
|
||||
} else {
|
||||
clearTimeout(lastFn);
|
||||
lastFn = setTimeout(function() {
|
||||
if (Date.now() - lastTime >= wait) {
|
||||
fn.apply(context, args);
|
||||
lastTime = Date.now();
|
||||
}
|
||||
}, wait - (Date.now() - lastTime));
|
||||
}
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
window.addEventListener(
|
||||
'resize',
|
||||
throttle(function(evt) {
|
||||
console.log(window.innerWidth);
|
||||
console.log(window.innerHeight);
|
||||
}, 250)
|
||||
); // Will log the window dimensions at most every 250ms
|
||||
```
|
||||
@ -2,6 +2,7 @@ anagrams:string,recursion
|
||||
arrayToHtmlList:browser,array
|
||||
ary:adapter,function
|
||||
atob:node,string,utility
|
||||
attempt:function
|
||||
average:math,array
|
||||
averageBy:math,array,function
|
||||
bind:function,object
|
||||
@ -32,6 +33,7 @@ createElement:browser,utility
|
||||
createEventHub:browser,event,advanced
|
||||
currentURL:browser,url
|
||||
curry:function,recursion
|
||||
debounce:function
|
||||
decapitalize:string,array
|
||||
deepClone:object,recursion
|
||||
deepFlatten:array,recursion
|
||||
@ -161,6 +163,7 @@ once:function
|
||||
onUserInputChange:browser,event,advanced
|
||||
orderBy:object,array
|
||||
over:adapter,function
|
||||
overArgs:adapter,function
|
||||
palindrome:string
|
||||
parseCookie:utility,string
|
||||
partial:function
|
||||
@ -169,6 +172,7 @@ partition:array,object,function
|
||||
percentile:math
|
||||
pick:object,array
|
||||
pickBy:object,array,function
|
||||
pipeAsyncFunctions:adapter,function,promise
|
||||
pipeFunctions:adapter,function
|
||||
pluralize:string
|
||||
powerset:math
|
||||
@ -184,6 +188,7 @@ randomIntArrayInRange:math,utility,random
|
||||
randomIntegerInRange:math,utility,random
|
||||
randomNumberInRange:math,utility,random
|
||||
readFileLines:node,array,string
|
||||
rearg:adapter,function
|
||||
redirect:browser,url
|
||||
reducedFilter:array
|
||||
reduceSuccessive:array,function
|
||||
@ -227,6 +232,7 @@ take:array
|
||||
takeRight:array
|
||||
takeRightWhile:array,function
|
||||
takeWhile:array,function
|
||||
throttle:function
|
||||
times:function
|
||||
timeTaken:utility
|
||||
toCamelCase:string,regexp
|
||||
|
||||
@ -6,9 +6,11 @@ test('Testing anagrams', (t) => {
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof anagrams === 'function', 'anagrams is a Function');
|
||||
t.deepEqual(anagrams('abc'), ['abc','acb','bac','bca','cab','cba'], "Generates all anagrams of a string");
|
||||
t.deepEqual(anagrams('a'), ['a'], "Works for single-letter strings");
|
||||
t.deepEqual(anagrams(''), [''], "Works for empty strings");
|
||||
//t.deepEqual(anagrams(args..), 'Expected');
|
||||
//t.equal(anagrams(args..), 'Expected');
|
||||
//t.false(anagrams(args..), 'Expected');
|
||||
//t.throws(anagrams(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
@ -5,9 +5,11 @@ test('Testing ary', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof ary === 'function', 'ary is a Function');
|
||||
const firstTwoMax = ary(Math.max, 2);
|
||||
t.deepEquals([[2, 6, 'a'], [8, 4, 6], [10]].map(x => firstTwoMax(...x)), [6, 8, 10], 'Discards arguments with index >=n')
|
||||
//t.deepEqual(ary(args..), 'Expected');
|
||||
//t.equal(ary(args..), 'Expected');
|
||||
//t.false(ary(args..), 'Expected');
|
||||
//t.throws(ary(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
8
test/attempt/attempt.js
Normal file
8
test/attempt/attempt.js
Normal file
@ -0,0 +1,8 @@
|
||||
const attempt = (fn, ...args) => {
|
||||
try {
|
||||
return fn(args);
|
||||
} catch (e) {
|
||||
return e instanceof Error ? e : new Error(e);
|
||||
}
|
||||
};
|
||||
module.exports = attempt
|
||||
15
test/attempt/attempt.test.js
Normal file
15
test/attempt/attempt.test.js
Normal file
@ -0,0 +1,15 @@
|
||||
const test = require('tape');
|
||||
const attempt = require('./attempt.js');
|
||||
|
||||
test('Testing attempt', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof attempt === 'function', 'attempt is a Function');
|
||||
t.equals(attempt(() => 0), 0, 'Returns a value');
|
||||
t.true(attempt(() => {throw new Error()}) instanceof Error, 'Returns an error');
|
||||
//t.deepEqual(attempt(args..), 'Expected');
|
||||
//t.equal(attempt(args..), 'Expected');
|
||||
//t.false(attempt(args..), 'Expected');
|
||||
//t.throws(attempt(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
@ -5,9 +5,15 @@ test('Testing bind', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof bind === 'function', 'bind is a Function');
|
||||
function greet(greeting, punctuation) {
|
||||
return greeting + ' ' + this.user + punctuation;
|
||||
}
|
||||
const freddy = { user: 'fred' };
|
||||
const freddyBound = bind(greet, freddy);
|
||||
t.equals(freddyBound('hi', '!'),'hi fred!', 'Binds to an object context');
|
||||
//t.deepEqual(bind(args..), 'Expected');
|
||||
//t.equal(bind(args..), 'Expected');
|
||||
//t.false(bind(args..), 'Expected');
|
||||
//t.throws(bind(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
const bindAll = (obj, ...fns) =>
|
||||
fns.forEach(
|
||||
fn =>
|
||||
fn => (
|
||||
(f = obj[fn]),
|
||||
(obj[fn] = function() {
|
||||
return fn.apply(obj);
|
||||
return f.apply(obj);
|
||||
})
|
||||
)
|
||||
);
|
||||
module.exports = bindAll
|
||||
@ -5,9 +5,17 @@ test('Testing bindAll', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof bindAll === 'function', 'bindAll is a Function');
|
||||
var view = {
|
||||
label: 'docs',
|
||||
'click': function() {
|
||||
return 'clicked ' + this.label;
|
||||
}
|
||||
}
|
||||
bindAll(view, 'click');
|
||||
t.equal(view.click(), 'clicked docs', 'Binds to an object context')
|
||||
//t.deepEqual(bindAll(args..), 'Expected');
|
||||
//t.equal(bindAll(args..), 'Expected');
|
||||
//t.false(bindAll(args..), 'Expected');
|
||||
//t.throws(bindAll(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
@ -5,9 +5,17 @@ test('Testing bindKey', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof bindKey === 'function', 'bindKey is a Function');
|
||||
const freddy = {
|
||||
user: 'fred',
|
||||
greet: function(greeting, punctuation) {
|
||||
return greeting + ' ' + this.user + punctuation;
|
||||
}
|
||||
};
|
||||
const freddyBound = bindKey(freddy, 'greet');
|
||||
t.equal(freddyBound('hi', '!'), 'hi fred!', 'Binds function to an object context');
|
||||
//t.deepEqual(bindKey(args..), 'Expected');
|
||||
//t.equal(bindKey(args..), 'Expected');
|
||||
//t.false(bindKey(args..), 'Expected');
|
||||
//t.throws(bindKey(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
@ -5,6 +5,9 @@ test('Testing byteSize', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof byteSize === 'function', 'byteSize is a Function');
|
||||
// Blob is not part of Node apparently?
|
||||
//t.equal(byteSize('Hello World'), 11, 'Works for text');
|
||||
//t.equal(byteSize('😀'), 4, 'Works for emojis');
|
||||
// Works only in browser
|
||||
// t.equal(byteSize('Hello World'), 11, "Returns the length of a string in bytes");
|
||||
//t.deepEqual(byteSize(args..), 'Expected');
|
||||
@ -12,4 +15,4 @@ test('Testing byteSize', (t) => {
|
||||
//t.false(byteSize(args..), 'Expected');
|
||||
//t.throws(byteSize(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
@ -5,9 +5,14 @@ test('Testing collectInto', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof collectInto === 'function', 'collectInto is a Function');
|
||||
const Pall = collectInto(Promise.all.bind(Promise));
|
||||
let p1 = Promise.resolve(1);
|
||||
let p2 = Promise.resolve(2);
|
||||
let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
|
||||
Pall(p1, p2, p3).then(function(val){ t.deepEqual(val, [1,2,3], 'Works with multiple promises')}, function(reason){});
|
||||
//t.deepEqual(collectInto(args..), 'Expected');
|
||||
//t.equal(collectInto(args..), 'Expected');
|
||||
//t.false(collectInto(args..), 'Expected');
|
||||
//t.throws(collectInto(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
@ -5,9 +5,11 @@ test('Testing countBy', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof countBy === 'function', 'countBy is a Function');
|
||||
t.deepEqual(countBy([6.1, 4.2, 6.3], Math.floor), {4: 1, 6: 2}, 'Works for functions');
|
||||
t.deepEqual(countBy(['one', 'two', 'three'], 'length'), {3: 2, 5: 1}, 'Works for property names');
|
||||
//t.deepEqual(countBy(args..), 'Expected');
|
||||
//t.equal(countBy(args..), 'Expected');
|
||||
//t.false(countBy(args..), 'Expected');
|
||||
//t.throws(countBy(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
10
test/debounce/debounce.js
Normal file
10
test/debounce/debounce.js
Normal file
@ -0,0 +1,10 @@
|
||||
const debounce = (fn, wait = 0) => {
|
||||
let inDebounce;
|
||||
return function() {
|
||||
const context = this,
|
||||
args = arguments;
|
||||
clearTimeout(inDebounce);
|
||||
inDebounce = setTimeout(() => fn.apply(context, args), wait);
|
||||
};
|
||||
};
|
||||
module.exports = debounce
|
||||
13
test/debounce/debounce.test.js
Normal file
13
test/debounce/debounce.test.js
Normal file
@ -0,0 +1,13 @@
|
||||
const test = require('tape');
|
||||
const debounce = require('./debounce.js');
|
||||
|
||||
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');
|
||||
//t.deepEqual(debounce(args..), 'Expected');
|
||||
//t.equal(debounce(args..), 'Expected');
|
||||
//t.false(debounce(args..), 'Expected');
|
||||
//t.throws(debounce(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
@ -5,9 +5,11 @@ test('Testing decapitalize', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof decapitalize === 'function', 'decapitalize is a Function');
|
||||
t.equal(decapitalize('FooBar'), 'fooBar', 'Works with default parameter');
|
||||
t.equal(decapitalize('FooBar', true), 'fOOBAR', 'Works with second parameter set to true');
|
||||
//t.deepEqual(decapitalize(args..), 'Expected');
|
||||
//t.equal(decapitalize(args..), 'Expected');
|
||||
//t.false(decapitalize(args..), 'Expected');
|
||||
//t.throws(decapitalize(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
@ -10,4 +10,4 @@ test('Testing dropWhile', (t) => {
|
||||
//t.false(dropWhile(args..), 'Expected');
|
||||
//t.throws(dropWhile(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
2
test/overArgs/overArgs.js
Normal file
2
test/overArgs/overArgs.js
Normal file
@ -0,0 +1,2 @@
|
||||
const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val)));
|
||||
module.exports = overArgs
|
||||
13
test/overArgs/overArgs.test.js
Normal file
13
test/overArgs/overArgs.test.js
Normal file
@ -0,0 +1,13 @@
|
||||
const test = require('tape');
|
||||
const overArgs = require('./overArgs.js');
|
||||
|
||||
test('Testing overArgs', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof overArgs === 'function', 'overArgs is a Function');
|
||||
//t.deepEqual(overArgs(args..), 'Expected');
|
||||
//t.equal(overArgs(args..), 'Expected');
|
||||
//t.false(overArgs(args..), 'Expected');
|
||||
//t.throws(overArgs(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
2
test/pipeAsyncFunctions/pipeAsyncFunctions.js
Normal file
2
test/pipeAsyncFunctions/pipeAsyncFunctions.js
Normal file
@ -0,0 +1,2 @@
|
||||
const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
|
||||
module.exports = pipeAsyncFunctions
|
||||
24
test/pipeAsyncFunctions/pipeAsyncFunctions.test.js
Normal file
24
test/pipeAsyncFunctions/pipeAsyncFunctions.test.js
Normal file
@ -0,0 +1,24 @@
|
||||
const test = require('tape');
|
||||
const pipeAsyncFunctions = require('./pipeAsyncFunctions.js');
|
||||
|
||||
test('Testing pipeAsyncFunctions', async (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof pipeAsyncFunctions === 'function', 'pipeAsyncFunctions is a Function');
|
||||
//t.deepEqual(pipeAsyncFunctions(args..), 'Expected');
|
||||
//t.equal(pipeAsyncFunctions(args..), 'Expected');
|
||||
//t.false(pipeAsyncFunctions(args..), 'Expected');
|
||||
//t.throws(pipeAsyncFunctions(args..), 'Expected');
|
||||
t.equal(
|
||||
await pipeAsyncFunctions(
|
||||
(x) => x + 1,
|
||||
(x) => new Promise((resolve) => setTimeout(() => resolve(x + 2), 0)),
|
||||
(x) => x + 3,
|
||||
async (x) => await x + 4,
|
||||
)
|
||||
(5),
|
||||
15,
|
||||
'pipeAsyncFunctions result should be 15'
|
||||
);
|
||||
t.end();
|
||||
});
|
||||
8
test/rearg/rearg.js
Normal file
8
test/rearg/rearg.js
Normal file
@ -0,0 +1,8 @@
|
||||
const rearg = (fn, indexes) => (...args) =>
|
||||
fn(
|
||||
...args.reduce(
|
||||
(acc, val, i) => ((acc[indexes.indexOf(i)] = val), acc),
|
||||
Array.from({ length: indexes.length })
|
||||
)
|
||||
);
|
||||
module.exports = rearg
|
||||
13
test/rearg/rearg.test.js
Normal file
13
test/rearg/rearg.test.js
Normal file
@ -0,0 +1,13 @@
|
||||
const test = require('tape');
|
||||
const rearg = require('./rearg.js');
|
||||
|
||||
test('Testing rearg', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof rearg === 'function', 'rearg is a Function');
|
||||
//t.deepEqual(rearg(args..), 'Expected');
|
||||
//t.equal(rearg(args..), 'Expected');
|
||||
//t.false(rearg(args..), 'Expected');
|
||||
//t.throws(rearg(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
@ -5,9 +5,19 @@ test('Testing round', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof round === 'function', 'round is a Function');
|
||||
t.equal(round(1.005, 2), 1.01, "Rounds a number to a specified amount of digits.");
|
||||
//t.equal(round(args..), 'Expected');
|
||||
//t.false(round(args..), 'Expected');
|
||||
//t.throws(round(args..), 'Expected');
|
||||
t.equal(round(1.005, 2), 1.01, "round(1.005, 2) returns 1.01");
|
||||
t.equal(round(123.3423345345345345344, 11), 123.34233453453, "round(123.3423345345345345344, 11) returns 123.34233453453");
|
||||
t.equal(round(3.342, 11), 3.342, "round(3.342, 11) returns 3.342");
|
||||
t.equal(round(1.005), 1, "round(1.005) returns 1");
|
||||
t.true(isNaN(round([1.005, 2])), 'round([1.005, 2]) returns NaN');
|
||||
t.true(isNaN(round('string')), 'round(string) returns NaN');
|
||||
t.true(isNaN(round()), 'round() returns NaN');
|
||||
t.true(isNaN(round(132, 413, 4134)), 'round(132, 413, 4134) returns NaN');
|
||||
t.true(isNaN(round({a: 132}, 413)), 'round({a: 132}, 413) returns NaN');
|
||||
|
||||
let start = new Date().getTime();
|
||||
round(123.3423345345345345344, 11);
|
||||
let end = new Date().getTime();
|
||||
t.true((end - start) < 2000, 'round(123.3423345345345345344, 11) takes less than 2s to run');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
21
test/throttle/throttle.js
Normal file
21
test/throttle/throttle.js
Normal file
@ -0,0 +1,21 @@
|
||||
const throttle = (fn, wait) => {
|
||||
let inThrottle, lastFn, lastTime;
|
||||
return function() {
|
||||
const context = this,
|
||||
args = arguments;
|
||||
if (!inThrottle) {
|
||||
fn.apply(context, args);
|
||||
lastTime = Date.now();
|
||||
inThrottle = true;
|
||||
} else {
|
||||
clearTimeout(lastFn);
|
||||
lastFn = setTimeout(function() {
|
||||
if (Date.now() - lastTime >= wait) {
|
||||
fn.apply(context, args);
|
||||
lastTime = Date.now();
|
||||
}
|
||||
}, wait - (Date.now() - lastTime));
|
||||
}
|
||||
};
|
||||
};
|
||||
module.exports = throttle
|
||||
13
test/throttle/throttle.test.js
Normal file
13
test/throttle/throttle.test.js
Normal file
@ -0,0 +1,13 @@
|
||||
const test = require('tape');
|
||||
const throttle = require('./throttle.js');
|
||||
|
||||
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.deepEqual(throttle(args..), 'Expected');
|
||||
//t.equal(throttle(args..), 'Expected');
|
||||
//t.false(throttle(args..), 'Expected');
|
||||
//t.throws(throttle(args..), 'Expected');
|
||||
t.end();
|
||||
});
|
||||
@ -5,13 +5,18 @@ test('Testing toCamelCase', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof toCamelCase === 'function', 'toCamelCase is a Function');
|
||||
t.equal(toCamelCase('some_database_field_name'), 'someDatabaseFieldName', "Converts a string to camelCase");
|
||||
t.equal(toCamelCase('Some label that needs to be camelized'), 'someLabelThatNeedsToBeCamelized', "Converts a string to camelCase");
|
||||
t.equal(toCamelCase('some-javascript-property'), 'someJavascriptProperty', "Converts a string to camelCase");
|
||||
t.equal(toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'), 'someMixedStringWithSpacesUnderscoresAndHyphens', "Converts a string to camelCase");
|
||||
//t.deepEqual(toCamelCase(args..), 'Expected');
|
||||
//t.equal(toCamelCase(args..), 'Expected');
|
||||
//t.false(toCamelCase(args..), 'Expected');
|
||||
//t.throws(toCamelCase(args..), 'Expected');
|
||||
t.equal(toCamelCase('some_database_field_name'), 'someDatabaseFieldName', "toCamelCase('some_database_field_name') returns someDatabaseFieldName");
|
||||
t.equal(toCamelCase('Some label that needs to be camelized'), 'someLabelThatNeedsToBeCamelized', "toCamelCase('Some label that needs to be camelized') returns someLabelThatNeedsToBeCamelized");
|
||||
t.equal(toCamelCase('some-javascript-property'), 'someJavascriptProperty', "toCamelCase('some-javascript-property') return someJavascriptProperty");
|
||||
t.equal(toCamelCase('some-mixed_string with spaces_underscores-and-hyphens'), 'someMixedStringWithSpacesUnderscoresAndHyphens', "toCamelCase('some-mixed_string with spaces_underscores-and-hyphens') returns someMixedStringWithSpacesUnderscoresAndHyphens");
|
||||
t.throws(() => toCamelCase(), 'toCamelCase() throws a error');
|
||||
t.throws(() => toCamelCase([]), 'toCamelCase([]) throws a error');
|
||||
t.throws(() => toCamelCase({}), 'toCamelCase({}) throws a error');
|
||||
t.throws(() => toCamelCase(123), 'toCamelCase(123) throws a error');
|
||||
|
||||
let start = new Date().getTime();
|
||||
toCamelCase('some-mixed_string with spaces_underscores-and-hyphens');
|
||||
let end = new Date().getTime();
|
||||
t.true((end - start) < 2000, 'toCamelCase(some-mixed_string with spaces_underscores-and-hyphens) takes less than 2s to run');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
@ -5,13 +5,18 @@ test('Testing toKebabCase', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof toKebabCase === 'function', 'toKebabCase is a Function');
|
||||
t.equal(toKebabCase('camelCase'), 'camel-case', "string converts to snake case");
|
||||
t.equal(toKebabCase('some text'), 'some-text', "string converts to snake case");
|
||||
t.equal(toKebabCase('some-mixed-string With spaces-underscores-and-hyphens'), 'some-mixed-string-with-spaces-underscores-and-hyphens', "string converts to snake case");
|
||||
t.equal(toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'), 'i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-some-xml-and-html', "string converts to snake case");
|
||||
//t.deepEqual(toKebabCase(args..), 'Expected');
|
||||
//t.equal(toKebabCase(args..), 'Expected');
|
||||
//t.false(toKebabCase(args..), 'Expected');
|
||||
//t.throws(toKebabCase(args..), 'Expected');
|
||||
t.equal(toKebabCase('camelCase'), 'camel-case', "toKebabCase('camelCase') returns camel-case");
|
||||
t.equal(toKebabCase('some text'), 'some-text', "toKebabCase('some text') returns some-text");
|
||||
t.equal(toKebabCase('some-mixed-string With spaces-underscores-and-hyphens'), 'some-mixed-string-with-spaces-underscores-and-hyphens', "toKebabCase('some-mixed-string With spaces-underscores-and-hyphens') returns some-mixed-string-with-spaces-underscores-and-hyphens");
|
||||
t.equal(toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'), 'i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-some-xml-and-html', "toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') returns i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-some-xml-and-html");
|
||||
t.equal(toKebabCase(), undefined, 'toKebabCase() return undefined');
|
||||
t.throws(() => toKebabCase([]), 'toKebabCase([]) throws an error');
|
||||
t.throws(() => toKebabCase({}), 'toKebabCase({}) throws an error');
|
||||
t.throws(() => toKebabCase(123), 'toKebabCase(123) throws an error');
|
||||
|
||||
let start = new Date().getTime();
|
||||
toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML')
|
||||
let end = new Date().getTime();
|
||||
t.true((end - start) < 2000, 'toKebabCase(IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML) takes less than 2s to run');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
@ -5,14 +5,20 @@ test('Testing toSafeInteger', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof toSafeInteger === 'function', 'toSafeInteger is a Function');
|
||||
t.true(Number(toSafeInteger(3.2)), 'Number(toSafeInteger(3.2)) is a number');
|
||||
t.equal(toSafeInteger(3.2), 3, "Converts a value to a safe integer");
|
||||
t.equal(toSafeInteger('4.2'), 4, "Converts a value to a safe integer");
|
||||
t.equal(toSafeInteger(4.6), 5, "Converts a value to a safe integer");
|
||||
t.equal(toSafeInteger(1.5), 2, "Converts a value to a safe integer");
|
||||
t.equal(toSafeInteger(Infinity), 9007199254740991, "Converts a value to a safe integer");
|
||||
//t.deepEqual(toSafeInteger(args..), 'Expected');
|
||||
//t.equal(toSafeInteger(args..), 'Expected');
|
||||
//t.false(toSafeInteger(args..), 'Expected');
|
||||
//t.throws(toSafeInteger(args..), 'Expected');
|
||||
t.equal(toSafeInteger('4.2'), 4, "toSafeInteger('4.2') returns 4");
|
||||
t.equal(toSafeInteger(4.6), 5, "toSafeInteger(4.6) returns 5");
|
||||
t.equal(toSafeInteger([]), 0, "toSafeInteger([]) returns 0");
|
||||
t.true(isNaN(toSafeInteger([1.5, 3124])), "isNaN(toSafeInteger([1.5, 3124])) is true");
|
||||
t.true(isNaN(toSafeInteger('string')), "isNaN(toSafeInteger('string')) is true");
|
||||
t.true(isNaN(toSafeInteger({})), "isNaN(toSafeInteger({})) is true");
|
||||
t.true(isNaN(toSafeInteger()), "isNaN(toSafeInteger()) is true");
|
||||
t.equal(toSafeInteger(Infinity), 9007199254740991, "toSafeInteger(Infinity) returns 9007199254740991");
|
||||
|
||||
let start = new Date().getTime();
|
||||
toSafeInteger(3.2);
|
||||
let end = new Date().getTime();
|
||||
t.true((end - start) < 2000, 'toSafeInteger(3.2) takes less than 2s to run');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
@ -5,14 +5,18 @@ test('Testing toSnakeCase', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof toSnakeCase === 'function', 'toSnakeCase is a Function');
|
||||
t.equal(toSnakeCase('camelCase'), 'camel_case', "string converts to snake case");
|
||||
t.equal(toSnakeCase('some text'), 'some_text', "string converts to snake case");
|
||||
t.equal(toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'), 'some_mixed_string_with_spaces_underscores_and_hyphens', "string converts to snake case");
|
||||
t.equal(toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'), 'i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html', "string converts to snake case");
|
||||
t.equal(toSnakeCase('camelCase'), 'camel_case', "toSnakeCase('camelCase') returns camel_case");
|
||||
t.equal(toSnakeCase('some text'), 'some_text', "toSnakeCase('some text') returns some_text");
|
||||
t.equal(toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'), 'some_mixed_string_with_spaces_underscores_and_hyphens', "toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens') returns some_mixed_string_with_spaces_underscores_and_hyphens");
|
||||
t.equal(toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'), 'i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html', "toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML') returns i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html");
|
||||
t.equal(toSnakeCase(), undefined, 'toSnakeCase() returns undefined');
|
||||
t.throws(() => toSnakeCase([]), 'toSnakeCase([]) throws an error');
|
||||
t.throws(() => toSnakeCase({}), 'toSnakeCase({}) throws an error');
|
||||
t.throws(() => toSnakeCase(123), 'toSnakeCase(123) throws an error');
|
||||
|
||||
//t.deepEqual(toSnakeCase(args..), 'Expected');
|
||||
//t.equal(toSnakeCase(args..), 'Expected');
|
||||
//t.false(toSnakeCase(args..), 'Expected');
|
||||
//t.throws(toSnakeCase(args..), 'Expected');
|
||||
let start = new Date().getTime();
|
||||
toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML');
|
||||
let end = new Date().getTime();
|
||||
t.true((end - start) < 2000, 'toSnakeCase(IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML) takes less than 2s to run');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
@ -5,10 +5,20 @@ test('Testing union', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof union === 'function', 'union is a Function');
|
||||
t.deepEqual(union([1, 2, 3], [4, 3, 2]), [1, 2, 3, 4], "Returns every element that exists in any of the two arrays once");
|
||||
//t.deepEqual(union(args..), 'Expected');
|
||||
//t.equal(union(args..), 'Expected');
|
||||
//t.false(union(args..), 'Expected');
|
||||
//t.throws(union(args..), 'Expected');
|
||||
t.deepEqual(union([1, 2, 3], [4, 3, 2]), [1, 2, 3, 4], "union([1, 2, 3], [4, 3, 2]) returns [1, 2, 3, 4]");
|
||||
t.deepEqual(union('str', 'asd'), [ 's', 't', 'r', 'a', 'd' ], "union('str', 'asd') returns [ 's', 't', 'r', 'a', 'd' ]");
|
||||
t.deepEqual(union([[], {}], [1, 2, 3]), [[], {}, 1, 2, 3], "union([[], {}], [1, 2, 3]) returns [[], {}, 1, 2, 3]");
|
||||
t.deepEqual(union([], []), [], "union([], []) returns []");
|
||||
t.throws(() => union(), 'union() throws an error');
|
||||
t.throws(() => union(true, 'str'), 'union(true, str) throws an error');
|
||||
t.throws(() => union('false', true), 'union(false, true) throws an error');
|
||||
t.throws(() => union(123, {}), 'union(123, {}) throws an error');
|
||||
t.throws(() => union([], {}), 'union([], {}) throws an error');
|
||||
t.throws(() => union(undefined, null), 'union(undefined, null) throws an error');
|
||||
|
||||
let start = new Date().getTime();
|
||||
union([1, 2, 3], [4, 3, 2]);
|
||||
let end = new Date().getTime();
|
||||
t.true((end - start) < 2000, 'union([1, 2, 3], [4, 3, 2]) takes less than 2s to run');
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
@ -5,10 +5,24 @@ test('Testing uniqueElements', (t) => {
|
||||
//For more information on all the methods supported by tape
|
||||
//Please go to https://github.com/substack/tape
|
||||
t.true(typeof uniqueElements === 'function', 'uniqueElements is a Function');
|
||||
t.deepEqual(uniqueElements([1, 2, 2, 3, 4, 4, 5]), [1,2,3,4,5], "Returns all unique values of an array");
|
||||
//t.deepEqual(uniqueElements(args..), 'Expected');
|
||||
//t.equal(uniqueElements(args..), 'Expected');
|
||||
//t.false(uniqueElements(args..), 'Expected');
|
||||
//t.throws(uniqueElements(args..), 'Expected');
|
||||
t.deepEqual(uniqueElements([1, 2, 2, 3, 4, 4, 5]), [1,2,3,4,5], "uniqueElements([1, 2, 2, 3, 4, 4, 5]) returns [1,2,3,4,5]");
|
||||
t.deepEqual(uniqueElements([1, 23, 53]), [1, 23, 53], "uniqueElements([1, 23, 53]) returns [1, 23, 53]");
|
||||
t.deepEqual(uniqueElements([true, 0, 1, false, false, undefined, null, '']), [true, 0, 1, false, undefined, null, ''], "uniqueElements([true, 0, 1, false, false, undefined, null, '']) returns [true, 0, 1, false, false, undefined, null, '']");
|
||||
t.deepEqual(uniqueElements(), [], "uniqueElements() returns []");
|
||||
t.deepEqual(uniqueElements(null), [], "uniqueElements(null) returns []");
|
||||
t.deepEqual(uniqueElements(undefined), [], "uniqueElements(undefined) returns []");
|
||||
t.deepEqual(uniqueElements('strt'), ['s', 't', 'r'], "uniqueElements('strt') returns ['s', 't', 'r']");
|
||||
t.throws(() => uniqueElements(1, 1, 2543, 534, 5), 'uniqueElements(1, 1, 2543, 534, 5) throws an error');
|
||||
t.throws(() => uniqueElements({}), 'uniqueElements({}) throws an error');
|
||||
t.throws(() => uniqueElements(true), 'uniqueElements(true) throws an error');
|
||||
t.throws(() => uniqueElements(false), 'uniqueElements(false) throws an error');
|
||||
|
||||
let start = new Date().getTime();
|
||||
uniqueElements([true, 0, 1, false, false, undefined, null, ''])
|
||||
let end = new Date().getTime();
|
||||
t.true((end - start) < 2000, 'uniqueElements([true, 0, 1, false, false, undefined, null]) takes less than 2s to run');
|
||||
|
||||
t.end();
|
||||
});
|
||||
});
|
||||
|
||||
uniqueElements([1, 2, 2, '1', 4, 4, 4, 5, true]); // [1,2,3,4,5]
|
||||
|
||||
Reference in New Issue
Block a user