`));
10 | ```
11 |
12 | ```js
13 | arrayToHtmlList(['item 1', 'item 2'], 'myListID');
14 | ```
--------------------------------------------------------------------------------
/snippets/cloneRegExp.md:
--------------------------------------------------------------------------------
1 | ### cloneRegExp
2 |
3 | Clones a regular expression.
4 |
5 | Use `new RegExp()`, `RegExp.source` and `RegExp.flags` to clone the given regular expression.
6 |
7 | ```js
8 | const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);
9 | ```
10 |
11 | ```js
12 | const regExp = /lorem ipsum/gi;
13 | const regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/fibonacci.zh.md:
--------------------------------------------------------------------------------
1 | ### 斐波那契
2 |
3 | 生成一个包含斐波那契数列的数组,直到第n项.
4 |
5 | 创建一个特定长度的空数组,初始化前两个值(`0`和`1`). 使用`array.reduce()`使用最后两个值的总和将值添加到数组中,除了前两个值之外.
6 |
7 | ```js
8 | const fibonacci = n =>
9 | Array.from({ length: n }).reduce(
10 | (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
11 | []
12 | );
13 | ```
14 |
15 | ```js
16 | fibonacci(6); // [0, 1, 1, 2, 3, 5]
17 | ```
--------------------------------------------------------------------------------
/snippets/functionName.md:
--------------------------------------------------------------------------------
1 | ### functionName
2 |
3 | Logs the name of a function.
4 |
5 | Use `console.debug()` and the `name` property of the passed method to log the method's name to the `debug` channel of the console.
6 |
7 | ```js
8 | const functionName = fn => (console.debug(fn.name), fn);
9 | ```
10 |
11 | ```js
12 | functionName(Math.max); // max (logged in debug channel of console)
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/getType.md:
--------------------------------------------------------------------------------
1 | ### getType
2 |
3 | Returns the native type of a value.
4 |
5 | Returns lowercased constructor name of value, `"undefined"` or `"null"` if value is `undefined` or `null`.
6 |
7 | ```js
8 | const getType = v =>
9 | v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
10 | ```
11 |
12 | ```js
13 | getType(new Set([1, 2, 3])); // 'set'
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/hasClass.md:
--------------------------------------------------------------------------------
1 | ### hasClass
2 |
3 | Returns `true` if the element has the specified class, `false` otherwise.
4 |
5 | Use `element.classList.contains()` to check if the element has the specified class.
6 |
7 | ```js
8 | const hasClass = (el, className) => el.classList.contains(className);
9 | ```
10 |
11 | ```js
12 | hasClass(document.querySelector('p.special'), 'special'); // true
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/invertKeyValues.zh.md:
--------------------------------------------------------------------------------
1 | ### invertkeyvalues
2 |
3 | 反转对象的键值对,而不会改变它.
4 |
5 | 使用`object.keys()`和`array.reduce()`反转对象的键值对.
6 |
7 | ```js
8 | const invertKeyValues = obj =>
9 | Object.keys(obj).reduce((acc, key) => {
10 | acc[obj[key]] = key;
11 | return acc;
12 | }, {});
13 | ```
14 |
15 | ```js
16 | invertKeyValues({ name: 'John', age: 20 }); // { 20: 'age', John: 'name' }
17 | ```
--------------------------------------------------------------------------------
/snippets/isLowerCase.md:
--------------------------------------------------------------------------------
1 | ### isLowerCase
2 |
3 | Checks if a string is lower case.
4 |
5 | Convert the given string to lower case, using `String.toLowerCase()` and compare it to the original.
6 |
7 | ```js
8 | const isLowerCase = str => str === str.toLowerCase();
9 | ```
10 |
11 | ```js
12 | isLowerCase('abc'); // true
13 | isLowerCase('a3@$'); // true
14 | isLowerCase('Ab4'); // false
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/randomNumberInRange.md:
--------------------------------------------------------------------------------
1 | ### randomNumberInRange
2 |
3 | Returns a random number in the specified range.
4 |
5 | Use `Math.random()` to generate a random value, map it to the desired range using multiplication.
6 |
7 | ```js
8 | const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
9 | ```
10 |
11 | ```js
12 | randomNumberInRange(2, 10); // 6.0211363285087005
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/show.md:
--------------------------------------------------------------------------------
1 | ### show
2 |
3 | Shows all the elements specified.
4 |
5 | Use the spread operator (`...`) and `Array.forEach()` to clear the `display` property for each element specified.
6 |
7 | ```js
8 | const show = (...el) => [...el].forEach(e => (e.style.display = ''));
9 | ```
10 |
11 | ```js
12 | show(...document.querySelectorAll('img')); // Shows all elements on the page
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/toDecimalMark.md:
--------------------------------------------------------------------------------
1 | ### toDecimalMark
2 |
3 | Use `toLocaleString()` to convert a float-point arithmetic to the [Decimal mark](https://en.wikipedia.org/wiki/Decimal_mark) form. It makes a comma separated string from a number.
4 |
5 | ```js
6 | const toDecimalMark = num => num.toLocaleString('en-US');
7 | ```
8 |
9 | ```js
10 | toDecimalMark(12305030388.9087); // "12,305,030,388.909"
11 | ```
12 |
--------------------------------------------------------------------------------
/snippets/bottomVisible.zh.md:
--------------------------------------------------------------------------------
1 | ### bottomvisible
2 |
3 | 回报`真正`如果页面底部可见,`假`除此以外.
4 |
5 | 使用`scrolly`,`scrollHeight属性`和`clientheight`以确定页面的底部是否可见.
6 |
7 | ```js
8 | const bottomVisible = () =>
9 | document.documentElement.clientHeight + window.scrollY >=
10 | (document.documentElement.scrollHeight ƜƜ document.documentElement.clientHeight);
11 | ```
12 |
13 | ```js
14 | bottomVisible(); // true
15 | ```
--------------------------------------------------------------------------------
/snippets/difference.md:
--------------------------------------------------------------------------------
1 | ### difference
2 |
3 | Returns the difference between two arrays.
4 |
5 | Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`.
6 |
7 | ```js
8 | const difference = (a, b) => {
9 | const s = new Set(b);
10 | return a.filter(x => !s.has(x));
11 | };
12 | ```
13 |
14 | ```js
15 | difference([1, 2, 3], [1, 2, 4]); // [3]
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/isTravisCI.zh.md:
--------------------------------------------------------------------------------
1 | ### istravisci
2 |
3 | 检查当前的环境是否[travis ci](https://travis-ci.org/).
4 |
5 | 检查当前环境是否有`特拉维斯`和`CI`环境变量 ([参考](https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables)).
6 |
7 | ```js
8 | const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
9 | ```
10 |
11 | ```js
12 | isTravisCI(); // true (if code is running on Travis CI)
13 | ```
--------------------------------------------------------------------------------
/snippets/isUpperCase.md:
--------------------------------------------------------------------------------
1 | ### isUpperCase
2 |
3 | Checks if a string is upper case.
4 |
5 | Convert the given string to upper case, using `String.toUpperCase()` and compare it to the original.
6 |
7 |
8 | ```js
9 | const isUpperCase = str => str === str.toUpperCase();
10 | ```
11 |
12 | ```js
13 | isUpperCase('ABC'); // true
14 | isLowerCase('A3@$'); // true
15 | isLowerCase('aB4'); // false
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/reverseString.md:
--------------------------------------------------------------------------------
1 | ### reverseString
2 |
3 | Reverses a string.
4 |
5 | Use the spread operator (`...`) and `Array.reverse()` to reverse the order of the characters in the string.
6 | Combine characters to get a string using `String.join('')`.
7 |
8 | ```js
9 | const reverseString = str => [...str].reverse().join('');
10 | ```
11 |
12 | ```js
13 | reverseString('foobar'); // 'raboof'
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/truthCheckCollection.zh.md:
--------------------------------------------------------------------------------
1 | ### truthcheckcollection
2 |
3 | 检查谓词(第二个参数)是否对集合的所有元素(第一个参数)是真实的.
4 |
5 | 使用`array.every()`检查每个通过的对象是否有指定的属性,如果它返回一个真值.
6 |
7 | ```js
8 | const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]);
9 | ```
10 |
11 | ```js
12 | truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true
13 | ```
--------------------------------------------------------------------------------
/test/toOrdinalSuffix/toOrdinalSuffix.js:
--------------------------------------------------------------------------------
1 | module.exports = toOrdinalSuffix = num => {
2 | const int = parseInt(num),
3 | digits = [int % 10, int % 100],
4 | ordinals = ['st', 'nd', 'rd', 'th'],
5 | oPattern = [1, 2, 3, 4],
6 | tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];
7 | return oPattern.includes(digits[0]) && !tPattern.includes(digits[1])
8 | ? int + ordinals[digits[0] - 1]
9 | : int + ordinals[3];
10 | };
--------------------------------------------------------------------------------
/snippets/compose.zh.md:
--------------------------------------------------------------------------------
1 | ### 撰写
2 |
3 | 执行从右到左的功能组合.
4 |
5 | 使用`array.reduce()`执行从右到左的函数组合. 最后(最右边的)函数可以接受一个或多个参数;其余的功能必须是一元的.
6 |
7 | ```js
8 | const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
9 | ```
10 |
11 | ```js
12 | const add5 = x => x + 5;
13 | const multiply = (x, y) => x * y;
14 | const multiplyAndAdd5 = compose(add5, multiply);
15 | multiplyAndAdd5(5, 2); // 15
16 | ```
--------------------------------------------------------------------------------
/snippets/findLast.md:
--------------------------------------------------------------------------------
1 | ### findLast
2 |
3 | Returns the last element for which the provided function returns a truthy value.
4 |
5 | Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.slice(-1)` to get the last one.
6 |
7 | ```js
8 | const findLast = (arr, fn) => arr.filter(fn).slice(-1);
9 | ```
10 |
11 | ```js
12 | findLast([1, 2, 3, 4], n => n % 2 === 1); // 3
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/forEachRight.zh.md:
--------------------------------------------------------------------------------
1 | ### foreachright
2 |
3 | 从数组的最后一个元素开始,为每个数组元素执行一次提供的函数.
4 |
5 | 使用`array.slice(0)`克隆给定的数组,`array.reverse()`扭转它和`array.foreach()`遍历倒排的数组.
6 |
7 | ```js
8 | const forEachRight = (arr, callback) =>
9 | arr
10 | .slice(0)
11 | .reverse()
12 | .forEach(callback);
13 | ```
14 |
15 | ```js
16 | forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'
17 | ```
--------------------------------------------------------------------------------
/snippets/maxBy.zh.md:
--------------------------------------------------------------------------------
1 | ### maxby
2 |
3 | 在使用提供的函数将每个元素映射到一个值之后,返回数组的最大值.
4 |
5 | 使用`array.map()`将每个元素映射到返回的值`FN`,`math.max()`获得最大价值.
6 |
7 | ```js
8 | const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
9 | ```
10 |
11 | ```js
12 | maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8
13 | maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8
14 | ```
--------------------------------------------------------------------------------
/snippets/minBy.zh.md:
--------------------------------------------------------------------------------
1 | ### minby
2 |
3 | 在使用提供的函数将每个元素映射到一个值之后,返回数组的最小值.
4 |
5 | 使用`array.map()`将每个元素映射到返回的值`FN`,`math.min()`获得最大价值.
6 |
7 | ```js
8 | const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
9 | ```
10 |
11 | ```js
12 | minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8
13 | minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8
14 | ```
--------------------------------------------------------------------------------
/snippets/objectToPairs.md:
--------------------------------------------------------------------------------
1 | ### objectToPairs
2 |
3 | Creates an array of key-value pair arrays from an object.
4 |
5 | Use `Object.keys()` and `Array.map()` to iterate over the object's keys and produce an array with key-value pairs.
6 |
7 | ```js
8 | const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]);
9 | ```
10 |
11 | ```js
12 | objectToPairs({ a: 1, b: 2 }); // [['a',1],['b',2]]
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/chunk.zh.md:
--------------------------------------------------------------------------------
1 | ### 块
2 |
3 | 将一个数组分块成指定大小的较小数组.
4 |
5 | 使用`array.from()`创建一个新的数组,适合将要生产的数据块`array.slice()`将新数组的每个元素映射到块的长度`尺寸`如果原始数组不能均匀分割,最后的块将包含剩余的元素.
6 |
7 | ```js
8 | const chunk = (arr, size) =>
9 | Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
10 | arr.slice(i * size, i * size + size)
11 | );
12 | ```
13 |
14 | ```js
15 | chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]
16 | ```
--------------------------------------------------------------------------------
/snippets/countOccurrences.md:
--------------------------------------------------------------------------------
1 | ### countOccurrences
2 |
3 | Counts the occurrences of a value in an array.
4 |
5 | Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array.
6 |
7 | ```js
8 | const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a + 0), 0);
9 | ```
10 |
11 | ```js
12 | countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/dropRight.md:
--------------------------------------------------------------------------------
1 | ### dropRight
2 |
3 | Returns a new array with `n` elements removed from the right.
4 |
5 | Use `Array.slice()` to slice the remove the specified number of elements from the right.
6 |
7 | ```js
8 | const dropRight = (arr, n = 1) => arr.slice(0, -n);
9 | ```
10 |
11 | ```js
12 | dropRight([1, 2, 3]); // [1,2]
13 | dropRight([1, 2, 3], 2); // [1]
14 | dropRight([1, 2, 3], 42); // []
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/median.zh.md:
--------------------------------------------------------------------------------
1 | ### 中位数
2 |
3 | 返回数字数组的中位数.
4 |
5 | 找到数组的中间,使用`中的Array.sort()`对数值进行排序. 如果返回中间数字`长度`是奇数,否则两个中间数的平均值.
6 |
7 | ```js
8 | const median = arr => {
9 | const mid = Math.floor(arr.length / 2),
10 | nums = [...arr].sort((a, b) => a - b);
11 | return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
12 | };
13 | ```
14 |
15 | ```js
16 | median([5, 6, 50, 1, -5]); // 5
17 | ```
--------------------------------------------------------------------------------
/snippets/serializeCookie.md:
--------------------------------------------------------------------------------
1 | ### serializeCookie
2 |
3 | Serialize a cookie name-value pair into a Set-Cookie header string.
4 |
5 | Use template literals and `encodeURIComponent()` to create the appropriate string.
6 |
7 | ```js
8 | const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;
9 | ```
10 |
11 | ```js
12 | serializeCookie('foo', 'bar'); // 'foo=bar'
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/symmetricDifference.zh.md:
--------------------------------------------------------------------------------
1 | ### 对称差
2 |
3 | 返回两个数组之间的对称差异.
4 |
5 | 创建一个`组`从每个数组中,然后使用`array.filter()`在他们每个人只保留价值不包含在另一个.
6 |
7 | ```js
8 | const symmetricDifference = (a, b) => {
9 | const sA = new Set(a),
10 | sB = new Set(b);
11 | return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];
12 | };
13 | ```
14 |
15 | ```js
16 | symmetricDifference([1, 2, 3], [1, 2, 4]); // [3,4]
17 | ```
--------------------------------------------------------------------------------
/snippets/toggleClass.md:
--------------------------------------------------------------------------------
1 | ### toggleClass
2 |
3 | Toggle a class for an element.
4 |
5 | Use `element.classList.toggle()` to toggle the specified class for the element.
6 |
7 | ```js
8 | const toggleClass = (el, className) => el.classList.toggle(className);
9 | ```
10 |
11 | ```js
12 | toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymore
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/coalesceFactory.zh.md:
--------------------------------------------------------------------------------
1 | ### coalescefactory
2 |
3 | 返回一个自定义的合并函数,返回返回的第一个参数`真正`从提供的参数验证功能.
4 |
5 | 使用`array.find()`返回返回的第一个参数`真正`从提供的参数验证功能.
6 |
7 | ```js
8 | const coalesceFactory = valid => (...args) => args.find(valid);
9 | ```
10 |
11 | ```js
12 | const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_));
13 | customCoalesce(undefined, null, NaN, '', 'Waldo'); // "Waldo"
14 | ```
--------------------------------------------------------------------------------
/snippets/detectDeviceType.zh.md:
--------------------------------------------------------------------------------
1 | ### detectdevicetype
2 |
3 | 检测到网站在移动设备或台式机/笔记本电脑上打开.
4 |
5 | 使用正则表达式来测试`navigator.userAgent的`财产来确定设备是移动设备还是台式机/笔记本电脑.
6 |
7 | ```js
8 | const detectDeviceType = () =>
9 | /AndroidƜwebOSƜiPhoneƜiPadƜiPodƜBlackBerryƜIEMobileƜOpera Mini/i.test(navigator.userAgent)
10 | ? 'Mobile'
11 | : 'Desktop';
12 | ```
13 |
14 | ```js
15 | detectDeviceType(); // "Mobile" or "Desktop"
16 | ```
--------------------------------------------------------------------------------
/snippets/intersection.md:
--------------------------------------------------------------------------------
1 | ### intersection
2 |
3 | Returns a list of elements that exist in both arrays.
4 |
5 | Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`.
6 |
7 | ```js
8 | const intersection = (a, b) => {
9 | const s = new Set(b);
10 | return a.filter(x => s.has(x));
11 | };
12 | ```
13 |
14 | ```js
15 | intersection([1, 2, 3], [4, 3, 2]); // [2,3]
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/lcm.zh.md:
--------------------------------------------------------------------------------
1 | ### LCM
2 |
3 | 返回两个或更多数字的最小公倍数.
4 |
5 | 使用最大公约数(gcd)公式和事实`lcm(x,y)= x * y / gcd(x,y)`确定最小公倍数. gcd公式使用递归.
6 |
7 | ```js
8 | const lcm = (...arr) => {
9 | const gcd = (x, y) => (!y ? x : gcd(y, x % y));
10 | const _lcm = (x, y) => x * y / gcd(x, y);
11 | return [...arr].reduce((a, b) => _lcm(a, b));
12 | };
13 | ```
14 |
15 | ```js
16 | lcm(12, 7); // 84
17 | lcm(...[1, 3, 4, 5]); // 60
18 | ```
--------------------------------------------------------------------------------
/snippets/powerset.md:
--------------------------------------------------------------------------------
1 | ### powerset
2 |
3 | Returns the powerset of a given array of numbers.
4 |
5 | Use `Array.reduce()` combined with `Array.map()` to iterate over elements and combine into an array containing all combinations.
6 |
7 | ```js
8 | const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);
9 | ```
10 |
11 | ```js
12 | powerset([1, 2]); // [[], [1], [2], [2,1]]
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/sample.md:
--------------------------------------------------------------------------------
1 | ### sample
2 |
3 | Returns a random element from an array.
4 |
5 | Use `Math.random()` to generate a random number, multiply it by `length` and round it of to the nearest whole number using `Math.floor()`.
6 | This method also works with strings.
7 |
8 | ```js
9 | const sample = arr => arr[Math.floor(Math.random() * arr.length)];
10 | ```
11 |
12 | ```js
13 | sample([3, 7, 9, 11]); // 9
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/timeTaken.zh.md:
--------------------------------------------------------------------------------
1 | ### 所用的时间
2 |
3 | 度量一个函数执行的时间.
4 |
5 | 使用`console.time()`和`console.timeend()`来衡量开始和结束时间之间的差异,以确定回调执行多长时间.
6 |
7 | ```js
8 | const timeTaken = callback => {
9 | console.time('timeTaken');
10 | const r = callback();
11 | console.timeEnd('timeTaken');
12 | return r;
13 | };
14 | ```
15 |
16 | ```js
17 | timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms
18 | ```
--------------------------------------------------------------------------------
/snippets/untildify.md:
--------------------------------------------------------------------------------
1 | ### untildify
2 |
3 | Converts a tilde path to an absolute path.
4 |
5 | Use `String.replace()` with a regular expression and `OS.homedir()` to replace the `~` in the start of the path with the home directory.
6 |
7 | ```js
8 | const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`);
9 | ```
10 |
11 | ```js
12 | untildify('~/node'); // '/Users/aUser/node'
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/JSONToFile.zh.md:
--------------------------------------------------------------------------------
1 | ### jsontofile
2 |
3 | 写一个json对象到一个文件.
4 |
5 | 使用`fs.writefile()`,模板文字和`json.stringify()`写一个`JSON`反对`以.json`文件.
6 |
7 | ```js
8 | const fs = require('fs');
9 | const JSONToFile = (obj, filename) =>
10 | fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
11 | ```
12 |
13 | ```js
14 | JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'
15 | ```
--------------------------------------------------------------------------------
/snippets/yesNo.zh.md:
--------------------------------------------------------------------------------
1 | ### YESNO
2 |
3 | 回报`真正`如果字符串是`ÿ`/`是`要么`假`如果字符串是`ñ`/`没有`.
4 |
5 | 使用`regexp.test()`检查字符串是否评估为`Y /是的`要么`N /无`. 第二个参数,`高清`将默认答案设置为`没有`.
6 |
7 | ```js
8 | const yesNo = (val, def = false) =>
9 | /^(yƜyes)$/i.test(val) ? true : /^(nƜno)$/i.test(val) ? false : def;
10 | ```
11 |
12 | ```js
13 | yesNo('Y'); // true
14 | yesNo('yes'); // true
15 | yesNo('No'); // false
16 | yesNo('Foo', true); // true
17 | ```
--------------------------------------------------------------------------------
/snippets/average.md:
--------------------------------------------------------------------------------
1 | ### average
2 |
3 | Returns the average of an of two or more numbers.
4 |
5 | Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
6 |
7 | ```js
8 | const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length;
9 | ```
10 |
11 | ```js
12 | average(...[1, 2, 3]); // 2
13 | average(1, 2, 3); // 2
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/randomIntegerInRange.md:
--------------------------------------------------------------------------------
1 | ### randomIntegerInRange
2 |
3 | Returns a random integer in the specified range.
4 |
5 | Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer.
6 |
7 | ```js
8 | const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
9 | ```
10 |
11 | ```js
12 | randomIntegerInRange(0, 5); // 2
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/round.md:
--------------------------------------------------------------------------------
1 | ### round
2 |
3 | Rounds a number to a specified amount of digits.
4 |
5 | Use `Math.round()` and template literals to round the number to the specified number of digits.
6 | Omit the second argument, `decimals` to round to an integer.
7 |
8 | ```js
9 | const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
10 | ```
11 |
12 | ```js
13 | round(1.005, 2); // 1.01
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/curry.zh.md:
--------------------------------------------------------------------------------
1 | ### 咖喱
2 |
3 | 咖喱功能.
4 |
5 | 使用递归. 如果提供的参数数量(`ARGS`)就足够了,调用传递函数`FN`. 另外,返回一个curried函数`FN`如果你想要一个接受可变数目参数的函数(一个可变参数函数,例如,`math.min()`),您可以选择将参数个数传递给第二个参数`元数`.
6 |
7 | ```js
8 | const curry = (fn, arity = fn.length, ...args) =>
9 | arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
10 | ```
11 |
12 | ```js
13 | curry(Math.pow)(2)(10); // 1024
14 | curry(Math.min, 3)(10)(50)(2); // 2
15 | ```
--------------------------------------------------------------------------------
/snippets/isObject.zh.md:
--------------------------------------------------------------------------------
1 | ### 则IsObject
2 |
3 | 返回一个布尔值,确定传递的值是否是一个对象.
4 |
5 | 使用`目的`构造函数为给定的值创建一个对象包装器. `如果价值是`空值`要么`未定义,创建并返回一个空的对象. 否则,返回对应于给定值的类型的对象.
6 |
7 | ```js
8 | const isObject = obj => obj === Object(obj);
9 | ```
10 |
11 | ```js
12 | isObject([1, 2, 3, 4]); // true
13 | isObject([]); // true
14 | isObject(['Hello!']); // true
15 | isObject({ a: 1 }); // true
16 | isObject({}); // true
17 | isObject(true); // false
18 | ```
--------------------------------------------------------------------------------
/snippets/mapKeys.zh.md:
--------------------------------------------------------------------------------
1 | ### 映射键
2 |
3 | 通过为每个键运行提供的功能和与提供的对象相同的值来创建具有键生成的对象.
4 |
5 | 使用`object.keys(OBJ)`遍历对象的keys.use`array.reduce()`使用相同的值和映射的键创建一个新的对象`FN`.
6 |
7 | ```js
8 | const mapKeys = (obj, fn) =>
9 | Object.keys(obj).reduce((acc, k) => {
10 | acc[fn(obj[k], k, obj)] = obj[k];
11 | return acc;
12 | }, {});
13 | ```
14 |
15 | ```js
16 | mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 }
17 | ```
--------------------------------------------------------------------------------
/snippets/sdbm.zh.md:
--------------------------------------------------------------------------------
1 | ### SBDM
2 |
3 | 将输入字符串散列为整数.
4 |
5 | 使用`string.split( '')`和`array.reduce()`创建输入字符串的散列,利用位移.
6 |
7 | ```js
8 | const sdbm = str => {
9 | let arr = str.split('');
10 | return arr.reduce(
11 | (hashCode, currentVal) =>
12 | (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode),
13 | 0
14 | );
15 | };
16 | ```
17 |
18 | ```js
19 | sdbm('name'); // -3521204949
20 | ```
--------------------------------------------------------------------------------
/snippets/capitalizeEveryWord.md:
--------------------------------------------------------------------------------
1 | ### capitalizeEveryWord
2 |
3 | Capitalizes the first letter of every word in a string.
4 |
5 | Use `String.replace()` to match the first character of each word and `String.toUpperCase()` to capitalize it.
6 |
7 | ```js
8 | const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
9 | ```
10 |
11 | ```js
12 | capitalizeEveryWord('hello world!'); // 'Hello World!'
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/collectInto.zh.md:
--------------------------------------------------------------------------------
1 | ### collectinto
2 |
3 | 将接受数组的函数改为可变函数.
4 |
5 | 给定一个函数,返回一个闭包,将所有输入收集到一个数组接受函数中.
6 |
7 | ```js
8 | const collectInto = fn => (...args) => fn(args);
9 | ```
10 |
11 | ```js
12 | const Pall = collectInto(Promise.all.bind(Promise));
13 | let p1 = Promise.resolve(1);
14 | let p2 = Promise.resolve(2);
15 | let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3));
16 | Pall(p1, p2, p3).then(console.log);
17 | ```
--------------------------------------------------------------------------------
/snippets/flip.zh.md:
--------------------------------------------------------------------------------
1 | ### 翻动
2 |
3 | flip将函数作为参数,然后将第一个参数作为最后一个参数.
4 |
5 | 返回一个包含可变参数的闭包,然后拼接最后一个参数,使其成为第一个参数,然后应用其余参数.
6 |
7 | ```js
8 | const flip = fn => (...args) => fn(args.pop(), ...args);
9 | ```
10 |
11 | ```js
12 | let a = { name: 'John Smith' };
13 | let b = {};
14 | const mergeFrom = flip(Object.assign);
15 | let mergePerson = mergeFrom.bind(null, a);
16 | mergePerson(b); // == b
17 | b = {};
18 | Object.assign(b, a); // == b
19 | ```
--------------------------------------------------------------------------------
/snippets/getDaysDiffBetweenDates.md:
--------------------------------------------------------------------------------
1 | ### getDaysDiffBetweenDates
2 |
3 | Returns the difference (in days) between two dates.
4 |
5 | Calculate the difference (in days) between two `Date` objects.
6 |
7 | ```js
8 | const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
9 | (dateFinal - dateInitial) / (1000 * 3600 * 24);
10 | ```
11 |
12 | ```js
13 | getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/indexOfAll.zh.md:
--------------------------------------------------------------------------------
1 | ### indexofall
2 |
3 | 返回所有的索引`VAL`在一个数组中. `如果`VAL`从不发生,返回`\[]
4 |
5 | . `使用`array.foreach()`循环元素和`的Array.push()存储匹配元素的索引. 返回索引数组.
6 |
7 | ```js
8 | const indexOfAll = (arr, val) => {
9 | const indices = [];
10 | arr.forEach((el, i) => el === val && indices.push(i));
11 | return indices;
12 | };
13 | ```
14 |
15 | ```js
16 | indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
17 | indexOfAll([1, 2, 3], 4); // []
18 | ```
--------------------------------------------------------------------------------
/snippets/setStyle.md:
--------------------------------------------------------------------------------
1 | ### setStyle
2 |
3 | Sets the value of a CSS rule for the specified element.
4 |
5 | Use `element.style` to set the value of the CSS rule for the specified element to `val`.
6 |
7 | ```js
8 | const setStyle = (el, ruleName, val) => (el.style[ruleName] = val);
9 | ```
10 |
11 | ```js
12 | setStyle(document.querySelector('p'), 'font-size', '20px'); // The first
element on the page will have a font-size of 20px
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/words.zh.md:
--------------------------------------------------------------------------------
1 | ### 话
2 |
3 | 将给定的字符串转换为单词数组.
4 |
5 | 使用`string.split()`与提供的模式(默认为非alpha作为正则表达式)转换为字符串数组. `使用`array.filter()删除任何空的strings.omit第二个参数使用默认的正则表达式.
6 |
7 | ```js
8 | const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
9 | ```
10 |
11 | ```js
12 | words('I love javaScript!!'); // ["I", "love", "javaScript"]
13 | words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"]
14 | ```
--------------------------------------------------------------------------------
/snippets_archive/removeVowels.md:
--------------------------------------------------------------------------------
1 | ### removeVowels
2 |
3 | Returns all the vowels in a `str` replaced by `repl`.
4 |
5 | Use `String.replace()` with a regexp to replace all vowels in `str`.
6 | Omot `repl` to use a default value of `''`.
7 |
8 | ```js
9 | const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl);
10 | ```
11 |
12 | ```js
13 | removeVowels("foobAr"); // "fbr"
14 | removeVowels("foobAr","*"); // "f**b*r"
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/chainAsync.zh.md:
--------------------------------------------------------------------------------
1 | ### chainasync
2 |
3 | 链异步功能.
4 |
5 | 循环遍历包含异步事件的函数数组,调用`下一个`当每个异步事件已经完成时.
6 |
7 | ```js
8 | const chainAsync = fns => {
9 | let curr = 0;
10 | const next = () => fns[curr++](next);
11 | next();
12 | };
13 | ```
14 |
15 | ```js
16 | chainAsync([
17 | next => {
18 | console.log('0 seconds');
19 | setTimeout(next, 1000);
20 | },
21 | next => {
22 | console.log('1 second');
23 | }
24 | ]);
25 | ```
--------------------------------------------------------------------------------
/snippets/isArrayLike.zh.md:
--------------------------------------------------------------------------------
1 | ### isarraylike
2 |
3 | 检查提供的参数是否类似于数组(即可迭代).
4 |
5 | 使用扩展运算符(`...`)来检查提供的参数是否可迭代`试着抓`块和逗号运算符(`,`)返回适当的值.
6 |
7 | ```js
8 | const isArrayLike = val => {
9 | try {
10 | return [...val], true;
11 | } catch (e) {
12 | return false;
13 | }
14 | };
15 | ```
16 |
17 | ```js
18 | isArrayLike(document.querySelectorAll('.className')); // true
19 | isArrayLike('abc'); // true
20 | isArrayLike(null); // false
21 | ```
--------------------------------------------------------------------------------
/snippets/pipeFunctions.zh.md:
--------------------------------------------------------------------------------
1 | ### pipefunctions
2 |
3 | 执行从左到右的功能组合.
4 |
5 | 使用`array.reduce()`与传播运算符(`...`)执行从左到右的函数组合. 第一个(最左边的)函数可以接受一个或多个参数;其余的功能必须是一元的.
6 |
7 | ```js
8 | const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
9 | ```
10 |
11 | ```js
12 | const add5 = x => x + 5;
13 | const multiply = (x, y) => x * y;
14 | const multiplyAndAdd5 = pipeFunctions(multiply, add5);
15 | multiplyAndAdd5(5, 2); // 15
16 | ```
--------------------------------------------------------------------------------
/snippets/randomHexColorCode.zh.md:
--------------------------------------------------------------------------------
1 | ### randomhexcolorcode
2 |
3 | 生成一个随机的十六进制颜色代码.
4 |
5 | 使用`的Math.random`生成一个随机的24位(6x4bits)十六进制数字. `使用位移,然后将其转换为十六进制字符串使用`的ToString(16).
6 |
7 | ```js
8 | const randomHexColorCode = () => {
9 | let n = ((Math.random() * 0xfffff) Ɯ 0).toString(16);
10 | return '#' + (n.length !== 6 ? ((Math.random() * 0xf) Ɯ 0).toString(16) + n : n);
11 | };
12 | ```
13 |
14 | ```js
15 | randomHexColorCode(); // "#e34155"
16 | ```
--------------------------------------------------------------------------------
/snippets/clampNumber.md:
--------------------------------------------------------------------------------
1 | ### clampNumber
2 |
3 | Clamps `num` within the inclusive range specified by the boundary values `a` and `b`.
4 |
5 | If `num` falls within the range, return `num`.
6 | Otherwise, return the nearest number in the range.
7 |
8 | ```js
9 | const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
10 | ```
11 |
12 | ```js
13 | clampNumber(2, 3, 5); // 3
14 | clampNumber(1, -1, -5); // -1
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/off.zh.md:
--------------------------------------------------------------------------------
1 | ### 离
2 |
3 | 从元素中移除一个事件监听器.
4 |
5 | 使用`eventtarget.removeeventlistener()`从元素中删除事件侦听器. `省略第四个参数`OPTS`使用`假或者根据添加事件侦听器时使用的选项来指定它.
6 |
7 | ```js
8 | const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);
9 | ```
10 |
11 | ```js
12 | const fn = () => console.log('!');
13 | document.body.addEventListener('click', fn);
14 | off(document.body, 'click', fn); // no longer logs '!' upon clicking on the page
15 | ```
--------------------------------------------------------------------------------
/snippets/tomorrow.md:
--------------------------------------------------------------------------------
1 | ### tomorrow
2 |
3 | Results in a string representation of tomorrow's date.
4 | Use `new Date()` to get today's date, adding `86400000` of seconds to it(24 hours), using `Date.toISOString()` to convert Date object to string.
5 |
6 | ```js
7 | const tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0];
8 | ```
9 |
10 | ```js
11 | tomorrow(); // 2017-12-27 (if current date is 2017-12-26)
12 | ```
13 |
--------------------------------------------------------------------------------
/snippets/zipObject.zh.md:
--------------------------------------------------------------------------------
1 | ### zipobject
2 |
3 | 给定一个有效的属性标识符和一个数组值的数组,返回一个将属性关联到值的对象.
4 |
5 | 因为一个对象可以有未定义的值,但是没有未定义的属性指针,所以这个属性数组用来决定使用结果对象的结构`array.reduce()`.
6 |
7 | ```js
8 | const zipObject = (props, values) =>
9 | props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {});
10 | ```
11 |
12 | ```js
13 | zipObject(['a', 'b', 'c'], [1, 2]); // {a: 1, b: 2, c: undefined}
14 | zipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2}
15 | ```
--------------------------------------------------------------------------------
/snippets/deepFlatten.md:
--------------------------------------------------------------------------------
1 | ### deepFlatten
2 |
3 | Deep flattens an array.
4 |
5 | Use recursion.
6 | Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.
7 | Recursively flatten each element that is an array.
8 |
9 | ```js
10 | const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
11 | ```
12 |
13 | ```js
14 | deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/getScrollPosition.zh.md:
--------------------------------------------------------------------------------
1 | ### 调用getScrollPosition
2 |
3 | 返回当前页面的滚动位置.
4 |
5 | 使用`pagexoffset`和`pageyoffset`如果他们被定义,否则`scrollleft`和`scrollTop的`你可以省略`埃尔`使用默认值`窗口`.
6 |
7 | ```js
8 | const getScrollPosition = (el = window) => ({
9 | x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
10 | y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
11 | });
12 | ```
13 |
14 | ```js
15 | getScrollPosition(); // {x: 0, y: 200}
16 | ```
--------------------------------------------------------------------------------
/snippets/isAbsoluteURL.md:
--------------------------------------------------------------------------------
1 | ### isAbsoluteURL
2 |
3 | Returns `true` if the given string is an absolute URL, `false` otherwise.
4 |
5 | Use a regular expression to test if the string is an absolute URL.
6 |
7 | ```js
8 | const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
9 | ```
10 |
11 | ```js
12 | isAbsoluteURL('https://google.com'); // true
13 | isAbsoluteURL('ftp://www.myserver.net'); // true
14 | isAbsoluteURL('/foo/bar'); // false
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/sumBy.zh.md:
--------------------------------------------------------------------------------
1 | ### sumby
2 |
3 | 在使用提供的函数将每个元素映射到一个值之后,返回一个数组的总和.
4 |
5 | 使用`array.map()`将每个元素映射到返回的值`FN`,`array.reduce()`将每个值添加到一个累加器,用一个值初始化`0`.
6 |
7 | ```js
8 | const sumBy = (arr, fn) =>
9 | arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0);
10 | ```
11 |
12 | ```js
13 | sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 20
14 | sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 20
15 | ```
--------------------------------------------------------------------------------
/snippets_archive/JSONToDate.md:
--------------------------------------------------------------------------------
1 | ### JSONToDate
2 |
3 | Converts a JSON object to a date.
4 |
5 | Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).
6 |
7 | ```js
8 | const JSONToDate = arr => {
9 | const dt = new Date(parseInt(arr.toString().substr(6)));
10 | return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
11 | };
12 | ```
13 |
14 | ```js
15 | JSONToDate(/Date(1489525200000)/); // "14/3/2017"
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets_archive/isArmstrongNumber.zh.md:
--------------------------------------------------------------------------------
1 | ### isarmstrongnumber
2 |
3 | 检查给定的号码是否是阿姆斯特朗号码.
4 |
5 | 将给定的数字转换为数字数组. `使用指数运算符(`\*\*`)为每个数字获得适当的权力并总结出来. `如果总和等于数字本身,则返回`真正`除此以外假.
6 |
7 | ```js
8 | const isArmstrongNumber = digits =>
9 | (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
10 | (digits + '').split('')
11 | );
12 | ```
13 |
14 | ```js
15 | isArmstrongNumber(1634); // true
16 | isArmstrongNumber(56); // false
17 | ```
--------------------------------------------------------------------------------
/snippets/RGBToHex.md:
--------------------------------------------------------------------------------
1 | ### RGBToHex
2 |
3 | Converts the values of RGB components to a color code.
4 |
5 | Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `String.padStart(6,'0')` to get a 6-digit hexadecimal value.
6 |
7 | ```js
8 | const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
9 | ```
10 |
11 | ```js
12 | RGBToHex(255, 165, 1); // 'ffa501'
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/call.zh.md:
--------------------------------------------------------------------------------
1 | ### 呼叫
2 |
3 | 给定一个关键和一组参数,给定一个上下文时调用它们.
4 |
5 | 主要用于构图. 使用闭包来调用存储的参数的存储键.
6 |
7 | ```js
8 | const call = (key, ...args) => context => context[key](...args);
9 | ```
10 |
11 | ```js
12 | Promise.resolve([1, 2, 3])
13 | .then(call('map', x => 2 * x))
14 | .then(console.log); //[ 2, 4, 6 ]
15 | const map = call.bind(null, 'map');
16 | Promise.resolve([1, 2, 3])
17 | .then(map(x => 2 * x))
18 | .then(console.log); //[ 2, 4, 6 ]
19 | ```
--------------------------------------------------------------------------------
/snippets/isValidJSON.zh.md:
--------------------------------------------------------------------------------
1 | ### isvalidjson
2 |
3 | 检查提供的参数是否是有效的json.
4 |
5 | 使用`JSON.parse()来`和a`试着抓`块来检查提供的参数是否是有效的json.
6 |
7 | ```js
8 | const isValidJSON = obj => {
9 | try {
10 | JSON.parse(obj);
11 | return true;
12 | } catch (e) {
13 | return false;
14 | }
15 | };
16 | ```
17 |
18 | ```js
19 | isValidJSON('{"name":"Adam","age":20}'); // true
20 | isValidJSON('{"name":"Adam",age:"20"}'); // false
21 | isValidJSON(null); // true
22 | ```
--------------------------------------------------------------------------------
/snippets/randomIntArrayInRange.zh.md:
--------------------------------------------------------------------------------
1 | ### randomintarrayinrange
2 |
3 | 返回指定范围内的n个随机整数的数组.
4 |
5 | 使用`array.from()`创建一个特定长度的空数组,`的Math.random()`生成一个随机数并将其映射到期望的范围,使用`math.floor()`使其成为一个整数.
6 |
7 | ```js
8 | const randomIntArrayInRange = (min, max, n = 1) =>
9 | Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
10 | ```
11 |
12 | ```js
13 | randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]
14 | ```
--------------------------------------------------------------------------------
/snippets/without.md:
--------------------------------------------------------------------------------
1 | ### without
2 |
3 | Filters out the elements of an array, that have one of the specified values.
4 |
5 | Use `Array.filter()` to create an array excluding(using `!Array.includes()`) all given values.
6 |
7 | _(For a snippet that mutates the original array see [`pull`](#pull))_
8 |
9 | ```js
10 | const without = (arr, ...args) => arr.filter(v => !args.includes(v));
11 | ```
12 |
13 | ```js
14 | without([2, 1, 2, 3], 1, 2); // [3]
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/capitalize.zh.md:
--------------------------------------------------------------------------------
1 | ### 利用
2 |
3 | 大写字符串的第一个字母.
4 |
5 | 使用数组解构和`string.touppercase()`首字母大写,`...休息`在第一个字母后再获取字符数组`array.join( '')`使它再次成为一个字符串`lowerrest`参数保持字符串的其余部分不变,或者将其设置为`真正`转换为小写.
6 |
7 | ```js
8 | const capitalize = ([first, ...rest], lowerRest = false) =>
9 | first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
10 | ```
11 |
12 | ```js
13 | capitalize('fooBar'); // 'FooBar'
14 | capitalize('fooBar', true); // 'Foobar'
15 | ```
--------------------------------------------------------------------------------
/snippets/redirect.md:
--------------------------------------------------------------------------------
1 | ### redirect
2 |
3 | Redirects to a specified URL.
4 |
5 | Use `window.location.href` or `window.location.replace()` to redirect to `url`.
6 | Pass a second argument to simulate a link click (`true` - default) or an HTTP redirect (`false`).
7 |
8 | ```js
9 | const redirect = (url, asLink = true) =>
10 | asLink ? (window.location.href = url) : window.location.replace(url);
11 | ```
12 |
13 | ```js
14 | redirect('https://google.com');
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/sortCharactersInString.md:
--------------------------------------------------------------------------------
1 | ### sortCharactersInString
2 |
3 | Alphabetically sorts the characters in a string.
4 |
5 | Use the spread operator (`...`), `Array.sort()` and `String.localeCompare()` to sort the characters in `str`, recombine using `String.join('')`.
6 |
7 | ```js
8 | const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
9 | ```
10 |
11 | ```js
12 | sortCharactersInString('cabbage'); // 'aabbceg'
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/spreadOver.md:
--------------------------------------------------------------------------------
1 | ### spreadOver
2 |
3 | Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.
4 |
5 | Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function.
6 |
7 | ```js
8 | const spreadOver = fn => argsArr => fn(...argsArr);
9 | ```
10 |
11 | ```js
12 | const arrayMax = spreadOver(Math.max);
13 | arrayMax([1, 2, 3]); // 3
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/toSafeInteger.md:
--------------------------------------------------------------------------------
1 | ### toSafeInteger
2 |
3 | Converts a value to a safe integer.
4 |
5 | Use `Math.max()` and `Math.min()` to find the closest safe value.
6 | Use `Math.round()` to convert to an integer.
7 |
8 | ```js
9 | const toSafeInteger = num =>
10 | Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));
11 | ```
12 |
13 | ```js
14 | toSafeInteger('3.2'); // 3
15 | toSafeInteger(Infinity); // 9007199254740991
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets_archive/fibonacciCountUntilNum.md:
--------------------------------------------------------------------------------
1 | ### fibonacciCountUntilNum
2 |
3 | Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive).
4 |
5 | Use a mathematical formula to calculate the number of fibonacci numbers until `num`.
6 |
7 | ```js
8 | const fibonacciCountUntilNum = num =>
9 | Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
10 | ```
11 |
12 | ```js
13 | fibonacciCountUntilNum(10); // 7
14 | ```
15 |
--------------------------------------------------------------------------------
/test/createEventHub/createEventHub.js:
--------------------------------------------------------------------------------
1 | module.exports = createEventHub = () => ({
2 | hub: Object.create(null),
3 | emit(event, data) {
4 | (this.hub[event] || []).forEach(handler => handler(data));
5 | },
6 | on(event, handler) {
7 | if (!this.hub[event]) this.hub[event] = [];
8 | this.hub[event].push(handler);
9 | },
10 | off(event, handler) {
11 | const i = (this.hub[event] || []).findIndex(h => h === handler);
12 | if (i > -1) this.hub[event].splice(i, 1);
13 | }
14 | });
--------------------------------------------------------------------------------
/test/runAsync/runAsync.js:
--------------------------------------------------------------------------------
1 | module.exports = runAsync = fn => {
2 | const blob = `var fn = ${fn.toString()}; postMessage(fn());`;
3 | const worker = new Worker(
4 | URL.createObjectURL(new Blob([blob]), {
5 | type: 'application/javascript; charset=utf-8'
6 | })
7 | );
8 | return new Promise((res, rej) => {
9 | worker.onmessage = ({ data }) => {
10 | res(data), worker.terminate();
11 | };
12 | worker.onerror = err => {
13 | rej(err), worker.terminate();
14 | };
15 | });
16 | };
--------------------------------------------------------------------------------
/snippets/initializeArrayWithValues.md:
--------------------------------------------------------------------------------
1 | ### initializeArrayWithValues
2 |
3 | Initializes and fills an array with the specified values.
4 |
5 | Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values.
6 | You can omit `val` to use a default value of `0`.
7 |
8 | ```js
9 | const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
10 | ```
11 |
12 | ```js
13 | initializeArrayWithValues(5, 2); // [2,2,2,2,2]
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/runPromisesInSeries.zh.md:
--------------------------------------------------------------------------------
1 | ### runpromisesinseries
2 |
3 | 运行一连串的承诺.
4 |
5 | 使用`array.reduce()`创建一个承诺链,每个承诺在解决时都会返回下一个承诺.
6 |
7 | ```js
8 | const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
9 | ```
10 |
11 | ```js
12 | const delay = d => new Promise(r => setTimeout(r, d));
13 | runPromisesInSeries([() => delay(1000), () => delay(2000)]); // Executes each promise sequentially, taking a total of 3 seconds to complete
14 | ```
--------------------------------------------------------------------------------
/snippets/transform.zh.md:
--------------------------------------------------------------------------------
1 | ### 转变
2 |
3 | 对累加器和对象中的每个键(从左到右)应用一个函数.
4 |
5 | 使用`object.keys(OBJ)`遍历对象中的每个键,`array.reduce()`调用对指定的累加器应用指定的函数.
6 |
7 | ```js
8 | const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
9 | ```
10 |
11 | ```js
12 | transform(
13 | { a: 1, b: 2, c: 1 },
14 | (r, v, k) => {
15 | (r[v] ƜƜ (r[v] = [])).push(k);
16 | return r;
17 | },
18 | {}
19 | ); // { '1': ['a', 'c'], '2': ['b'] }
20 | ```
--------------------------------------------------------------------------------
/snippets/sleep.md:
--------------------------------------------------------------------------------
1 | ### sleep
2 |
3 | Delays the execution of an asynchronous function.
4 |
5 | Delay executing part of an `async` function, by putting it to sleep, returning a `Promise`.
6 |
7 | ```js
8 | const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
9 | ```
10 |
11 | ```js
12 | async function sleepyWork() {
13 | console.log("I'm going to sleep for 1 second.");
14 | await sleep(1000);
15 | console.log('I woke up after 1 second.');
16 | }
17 | ```
18 |
--------------------------------------------------------------------------------
/test/on/on.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const on = require('./on.js');
3 |
4 | test('Testing on', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof on === 'function', 'on is a Function');
8 | //t.deepEqual(on(args..), 'Expected');
9 | //t.equal(on(args..), 'Expected');
10 | //t.false(on(args..), 'Expected');
11 | //t.throws(on(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/snippets/JSONToFile.md:
--------------------------------------------------------------------------------
1 | ### JSONToFile
2 |
3 | Writes a JSON object to a file.
4 |
5 | Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file.
6 |
7 | ```js
8 | const fs = require('fs');
9 | const JSONToFile = (obj, filename) =>
10 | fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
11 | ```
12 |
13 | ```js
14 | JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/arrayToHtmlList.md:
--------------------------------------------------------------------------------
1 | ### arrayToHtmlList
2 |
3 | Converts the given array elements into `
` tags and appends them to the list of the given id.
4 |
5 | Use `Array.map()` and `document.querySelector()` to create a list of html tags.
6 |
7 | ```js
8 | const arrayToHtmlList = (arr, listID) =>
9 | arr.map(item => (document.querySelector('#' + listID).innerHTML += `
${item}
`));
10 | ```
11 |
12 | ```js
13 | arrayToHtmlList(['item 1', 'item 2'], 'myListID');
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/inRange.zh.md:
--------------------------------------------------------------------------------
1 | ### 在范围内
2 |
3 | 检查给定的数字是否落在给定范围内.
4 |
5 | 使用算术比较来检查给定的数字是否在指定的范围内. 如果第二个参数,`结束`,没有指定,范围被认为是从`0`至`开始`.
6 |
7 | ```js
8 | const inRange = (n, start, end = null) => {
9 | if (end && start > end) end = [start, (start = end)][0];
10 | return end == null ? n >= 0 && n < start : n >= start && n < end;
11 | };
12 | ```
13 |
14 | ```js
15 | inRange(3, 2, 5); // true
16 | inRange(3, 4); // true
17 | inRange(2, 3, 5); // false
18 | inrange(3, 2); // false
19 | ```
--------------------------------------------------------------------------------
/test/formatDuration/formatDuration.js:
--------------------------------------------------------------------------------
1 | module.exports = formatDuration = ms => {
2 | if (ms < 0) ms = -ms;
3 | const time = {
4 | day: Math.floor(ms / 86400000),
5 | hour: Math.floor(ms / 3600000) % 24,
6 | minute: Math.floor(ms / 60000) % 60,
7 | second: Math.floor(ms / 1000) % 60,
8 | millisecond: Math.floor(ms) % 1000
9 | };
10 | return Object.entries(time)
11 | .filter(val => val[1] !== 0)
12 | .map(val => val[1] + ' ' + (val[1] !== 1 ? val[0] + 's' : val[0]))
13 | .join(', ');
14 | };
--------------------------------------------------------------------------------
/snippets/UUIDGeneratorBrowser.zh.md:
--------------------------------------------------------------------------------
1 | ### uuidgeneratorbrowser
2 |
3 | 在浏览器中生成一个uuid.
4 |
5 | 使用`加密`API生成一个UUID,符合[rfc4122](https://www.ietf.org/rfc/rfc4122.txt)版本4.
6 |
7 | ```js
8 | const UUIDGeneratorBrowser = () =>
9 | ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
10 | (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
11 | );
12 | ```
13 |
14 | ```js
15 | UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
16 | ```
--------------------------------------------------------------------------------
/snippets/decapitalize.zh.md:
--------------------------------------------------------------------------------
1 | ### decapitalize
2 |
3 | 将字符串的第一个字母去除.
4 |
5 | 使用数组解构和`string.tolowercase()`给首字母去封顶,`...休息`在第一个字母后再获取字符数组`array.join( '')`使它再次成为一个字符串`upperrest`参数保持字符串的其余部分不变,或者将其设置为`真正`转换为大写.
6 |
7 | ```js
8 | const decapitalize = ([first, ...rest], upperRest = false) =>
9 | first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
10 | ```
11 |
12 | ```js
13 | decapitalize('FooBar'); // 'fooBar'
14 | decapitalize('FooBar', true); // 'fOOBAR'
15 | ```
--------------------------------------------------------------------------------
/snippets/invertKeyValues.md:
--------------------------------------------------------------------------------
1 | ### invertKeyValues
2 |
3 | Inverts the key-value pairs of an object, without mutating it.
4 |
5 | Use `Object.keys()` and `Array.reduce()` to invert the key-value pairs of an object.
6 |
7 | ```js
8 | const invertKeyValues = obj =>
9 | Object.keys(obj).reduce((acc, key) => {
10 | acc[obj[key]] = key;
11 | return acc;
12 | }, {});
13 | ```
14 |
15 | ```js
16 | invertKeyValues({ name: 'John', age: 20 }); // { 20: 'age', John: 'name' }
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/pick.md:
--------------------------------------------------------------------------------
1 | ### pick
2 |
3 | Picks the key-value pairs corresponding to the given keys from an object.
4 |
5 | Use `Array.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pair if the key exists in the obj.
6 |
7 | ```js
8 | const pick = (obj, arr) =>
9 | arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
10 | ```
11 |
12 | ```js
13 | pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 }
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/remove.zh.md:
--------------------------------------------------------------------------------
1 | ### 去掉
2 |
3 | 从给定函数返回的数组中移除元素`假`.
4 |
5 | 使用`array.filter()`找到返回真值的数组元素`array.reduce()`使用删除元素`方法Array.splice()`.the`FUNC`被调用三个参数(`值,索引,数组`).
6 |
7 | ```js
8 | const remove = (arr, func) =>
9 | Array.isArray(arr)
10 | ? arr.filter(func).reduce((acc, val) => {
11 | arr.splice(arr.indexOf(val), 1);
12 | return acc.concat(val);
13 | }, [])
14 | : [];
15 | ```
16 |
17 | ```js
18 | remove([1, 2, 3, 4], n => n % 2 == 0); // [2, 4]
19 | ```
--------------------------------------------------------------------------------
/snippets/shuffle.zh.md:
--------------------------------------------------------------------------------
1 | ### 拖曳
2 |
3 | 随机化一个数组的值的顺序,返回一个新的数组.
4 |
5 | 使用[fisher-yates算法](https://github.com/chalarangelo/30-seconds-of-code#shuffle)重新排列数组的元素.
6 |
7 | ```js
8 | const shuffle = ([...arr]) => {
9 | let m = arr.length;
10 | while (m) {
11 | const i = Math.floor(Math.random() * m--);
12 | [arr[m], arr[i]] = [arr[i], arr[m]];
13 | }
14 | return arr;
15 | };
16 | ```
17 |
18 | ```js
19 | const foo = [1, 2, 3];
20 | shuffle(foo); // [2,3,1], foo = [1,2,3]
21 | ```
--------------------------------------------------------------------------------
/snippets/sortedIndex.zh.md:
--------------------------------------------------------------------------------
1 | ### sortedindex
2 |
3 | 返回值应该插入到数组中的最低索引,以保持其排序顺序.
4 |
5 | 检查数组是否按降序(松散地)排序`array.findindex()`找到元素应该被插入的适当的索引.
6 |
7 | ```js
8 | const sortedIndex = (arr, n) => {
9 | const isDescending = arr[0] > arr[arr.length - 1];
10 | const index = arr.findIndex(el => (isDescending ? n >= el : n <= el));
11 | return index === -1 ? arr.length : index;
12 | };
13 | ```
14 |
15 | ```js
16 | sortedIndex([5, 3, 2, 1], 4); // 1
17 | sortedIndex([30, 50], 40); // 1
18 | ```
--------------------------------------------------------------------------------
/test/off/off.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const off = require('./off.js');
3 |
4 | test('Testing off', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof off === 'function', 'off is a Function');
8 | //t.deepEqual(off(args..), 'Expected');
9 | //t.equal(off(args..), 'Expected');
10 | //t.false(off(args..), 'Expected');
11 | //t.throws(off(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/snippets/UUIDGeneratorNode.zh.md:
--------------------------------------------------------------------------------
1 | ### uuidgeneratornode
2 |
3 | 在node.js中生成一个uuid
4 |
5 | 使用`加密`API生成一个UUID,符合[rfc4122](https://www.ietf.org/rfc/rfc4122.txt)版本4.
6 |
7 | ```js
8 | const crypto = require('crypto');
9 | const UUIDGeneratorNode = () =>
10 | ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
11 | (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
12 | );
13 | ```
14 |
15 | ```js
16 | UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc'
17 | ```
--------------------------------------------------------------------------------
/snippets/bottomVisible.md:
--------------------------------------------------------------------------------
1 | ### bottomVisible
2 |
3 | Returns `true` if the bottom of the page is visible, `false` otherwise.
4 |
5 | Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.
6 |
7 | ```js
8 | const bottomVisible = () =>
9 | document.documentElement.clientHeight + window.scrollY >=
10 | (document.documentElement.scrollHeight || document.documentElement.clientHeight);
11 | ```
12 |
13 | ```js
14 | bottomVisible(); // true
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/differenceWith.md:
--------------------------------------------------------------------------------
1 | ### differenceWith
2 |
3 | Filters out all values from an array for which the comparator function does not return `true`.
4 |
5 | Use `Array.filter()` and `Array.findIndex()` to find the appropriate values.
6 |
7 | ```js
8 | const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
9 | ```
10 |
11 | ```js
12 | differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2]
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/extendHex.zh.md:
--------------------------------------------------------------------------------
1 | ### extendhex
2 |
3 | 将3位数的颜色代码扩展为6位数的颜色代码.
4 |
5 | 使用`array.map()`,`string.split()`和`array.join()`加入映射数组,将3位rgb注释的十六进制颜色代码转换为6位数形式. `array.slice()`是用来删除`#`从字符串开始,因为它被添加一次.
6 |
7 | ```js
8 | const extendHex = shortHex =>
9 | '#' +
10 | shortHex
11 | .slice(shortHex.startsWith('#') ? 1 : 0)
12 | .split('')
13 | .map(x => x + x)
14 | .join('');
15 | ```
16 |
17 | ```js
18 | extendHex('#03f'); // '#0033ff'
19 | extendHex('05a'); // '#0055aa'
20 | ```
--------------------------------------------------------------------------------
/snippets/hammingDistance.md:
--------------------------------------------------------------------------------
1 | ### hammingDistance
2 |
3 | Calculates the Hamming distance between two values.
4 |
5 | Use XOR operator (`^`) to find the bit difference between the two numbers, convert to a binary string using `toString(2)`.
6 | Count and return the number of `1`s in the string, using `match(/1/g)`.
7 |
8 | ```js
9 | const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;
10 | ```
11 |
12 | ```js
13 | hammingDistance(2, 3); // 1
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/isPrimitive.zh.md:
--------------------------------------------------------------------------------
1 | ### isprimitive
2 |
3 | 返回一个布尔值,判断传入的值是否为原始值.
4 |
5 | 使用`array.includes()`在一个非原始类型的字符串数组上,提供使用的类型`类型`. 以来`typeof null`评估`'目的'`,需要直接比较.
6 |
7 | ```js
8 | const isPrimitive = val => !['object', 'function'].includes(typeof val) ƜƜ val === null;
9 | ```
10 |
11 | ```js
12 | isPrimitive(null); // true
13 | isPrimitive(50); // true
14 | isPrimitive('Hello!'); // true
15 | isPrimitive(false); // true
16 | isPrimitive(Symbol()); // true
17 | isPrimitive([]); // false
18 | ```
--------------------------------------------------------------------------------
/snippets/isTravisCI.md:
--------------------------------------------------------------------------------
1 | ### isTravisCI
2 |
3 | Checks if the current environment is [Travis CI](https://travis-ci.org/).
4 |
5 | Checks if the current environment has the `TRAVIS` and `CI` environment variables ([reference](https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables)).
6 |
7 | ```js
8 | const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
9 | ```
10 |
11 | ```js
12 | isTravisCI(); // true (if code is running on Travis CI)
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/scrollToTop.zh.md:
--------------------------------------------------------------------------------
1 | ### 滚动到顶部
2 |
3 | 平滑滚动到页面的顶部.
4 |
5 | 从顶部使用距离`document.documentelement.scrolltop`要么`的document.body.scrollTop`. 从顶部的距离的一小部分. `使用`window.requestanimationframe()滚动动画.
6 |
7 | ```js
8 | const scrollToTop = () => {
9 | const c = document.documentElement.scrollTop ƜƜ document.body.scrollTop;
10 | if (c > 0) {
11 | window.requestAnimationFrame(scrollToTop);
12 | window.scrollTo(0, c - c / 8);
13 | }
14 | };
15 | ```
16 |
17 | ```js
18 | scrollToTop();
19 | ```
--------------------------------------------------------------------------------
/snippets/truncateString.md:
--------------------------------------------------------------------------------
1 | ### truncateString
2 |
3 | Truncates a string up to a specified length.
4 |
5 | Determine if the string's `length` is greater than `num`.
6 | Return the string truncated to the desired length, with `'...'` appended to the end or the original string.
7 |
8 | ```js
9 | const truncateString = (str, num) =>
10 | str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
11 | ```
12 |
13 | ```js
14 | truncateString('boomerang', 7); // 'boom...'
15 | ```
16 |
--------------------------------------------------------------------------------
/snippets/validateNumber.md:
--------------------------------------------------------------------------------
1 | ### validateNumber
2 |
3 | Returns `true` if the given value is a number, `false` otherwise.
4 |
5 | Use `!isNaN()` in combination with `parseFloat()` to check if the argument is a number.
6 | Use `isFinite()` to check if the number is finite.
7 | Use `Number()` to check if the coercion holds.
8 |
9 | ```js
10 | const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
11 | ```
12 |
13 | ```js
14 | validateNumber('10'); // true
15 | ```
16 |
--------------------------------------------------------------------------------
/test/call/call.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const call = require('./call.js');
3 |
4 | test('Testing call', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof call === 'function', 'call is a Function');
8 | //t.deepEqual(call(args..), 'Expected');
9 | //t.equal(call(args..), 'Expected');
10 | //t.false(call(args..), 'Expected');
11 | //t.throws(call(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/flip/flip.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const flip = require('./flip.js');
3 |
4 | test('Testing flip', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof flip === 'function', 'flip is a Function');
8 | //t.deepEqual(flip(args..), 'Expected');
9 | //t.equal(flip(args..), 'Expected');
10 | //t.false(flip(args..), 'Expected');
11 | //t.throws(flip(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/hide/hide.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const hide = require('./hide.js');
3 |
4 | test('Testing hide', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof hide === 'function', 'hide is a Function');
8 | //t.deepEqual(hide(args..), 'Expected');
9 | //t.equal(hide(args..), 'Expected');
10 | //t.false(hide(args..), 'Expected');
11 | //t.throws(hide(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/once/once.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const once = require('./once.js');
3 |
4 | test('Testing once', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof once === 'function', 'once is a Function');
8 | //t.deepEqual(once(args..), 'Expected');
9 | //t.equal(once(args..), 'Expected');
10 | //t.false(once(args..), 'Expected');
11 | //t.throws(once(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/pull/pull.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const pull = require('./pull.js');
3 |
4 | test('Testing pull', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof pull === 'function', 'pull is a Function');
8 | //t.deepEqual(pull(args..), 'Expected');
9 | //t.equal(pull(args..), 'Expected');
10 | //t.false(pull(args..), 'Expected');
11 | //t.throws(pull(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/show/show.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const show = require('./show.js');
3 |
4 | test('Testing show', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof show === 'function', 'show is a Function');
8 | //t.deepEqual(show(args..), 'Expected');
9 | //t.equal(show(args..), 'Expected');
10 | //t.false(show(args..), 'Expected');
11 | //t.throws(show(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/snippets/initialize2DArray.md:
--------------------------------------------------------------------------------
1 | ### initialize2DArray
2 |
3 | Initializes a 2D array of given width and height and value.
4 |
5 | Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`.
6 |
7 | ```js
8 | const initialize2DArray = (w, h, val = null) =>
9 | Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val));
10 | ```
11 |
12 | ```js
13 | initialize2DArray(2, 2, 0); // [[0,0], [0,0]]
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/averageBy.zh.md:
--------------------------------------------------------------------------------
1 | ### averageby
2 |
3 | 在使用提供的函数将每个元素映射到一个值之后,返回数组的平均值.
4 |
5 | 使用`array.map()`将每个元素映射到返回的值`FN`,`array.reduce()`将每个值添加到一个累加器,用一个值初始化`0`,除以`长度`的数组.
6 |
7 | ```js
8 | const averageBy = (arr, fn) =>
9 | arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
10 | arr.length;
11 | ```
12 |
13 | ```js
14 | averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5
15 | averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5
16 | ```
--------------------------------------------------------------------------------
/test/elementIsVisibleInViewport/elementIsVisibleInViewport.js:
--------------------------------------------------------------------------------
1 | module.exports = elementIsVisibleInViewport = (el, partiallyVisible = false) => {
2 | const { top, left, bottom, right } = el.getBoundingClientRect();
3 | const { innerHeight, innerWidth } = window;
4 | return partiallyVisible
5 | ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
6 | ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
7 | : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
8 | };
--------------------------------------------------------------------------------
/test/prettyBytes/prettyBytes.js:
--------------------------------------------------------------------------------
1 | module.exports = prettyBytes = (num, precision = 3, addSpace = true) => {
2 | const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
3 | if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];
4 | const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1);
5 | const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision));
6 | return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];
7 | };
--------------------------------------------------------------------------------
/snippets/hasFlags.zh.md:
--------------------------------------------------------------------------------
1 | ### hasflags
2 |
3 | 检查当前进程的参数是否包含指定的标志.
4 |
5 | 使用`array.every()`和`array.includes()`检查是否`process.argv`包含所有指定的标志. 使用正则表达式来测试指定的标志是否带有前缀`-`要么`-`并相应地加上前缀.
6 |
7 | ```js
8 | const hasFlags = (...flags) =>
9 | flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));
10 | ```
11 |
12 | ```js
13 | // node myScript.js -s --test --cool=true
14 | hasFlags('-s'); // true
15 | hasFlags('--test', 'cool=true', '-s'); // true
16 | hasFlags('special'); // false
17 | ```
--------------------------------------------------------------------------------
/snippets/mapObject.zh.md:
--------------------------------------------------------------------------------
1 | ### MapObject的
2 |
3 | 使用函数将数组的值映射到对象,其中键 - 值对由原始值作为键和映射值组成.
4 |
5 | 使用匿名内部函数作用域来声明未定义的内存空间,使用闭包来存储返回值. `使用新的`排列将函数的映射存储在数据集上,使用逗号运算符返回第二个步骤,而不需要从一个上下文移动到另一个上下文(由于关闭和操作顺序).
6 |
7 | ```js
8 | const mapObject = (arr, fn) =>
9 | (a => (
10 | (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
11 | ))();
12 | ```
13 |
14 | ```js
15 | const squareIt = arr => mapObject(arr, a => a * a);
16 | squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
17 | ```
--------------------------------------------------------------------------------
/test/defer/defer.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const defer = require('./defer.js');
3 |
4 | test('Testing defer', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof defer === 'function', 'defer is a Function');
8 | //t.deepEqual(defer(args..), 'Expected');
9 | //t.equal(defer(args..), 'Expected');
10 | //t.false(defer(args..), 'Expected');
11 | //t.throws(defer(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/maxBy/maxBy.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const maxBy = require('./maxBy.js');
3 |
4 | test('Testing maxBy', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof maxBy === 'function', 'maxBy is a Function');
8 | //t.deepEqual(maxBy(args..), 'Expected');
9 | //t.equal(maxBy(args..), 'Expected');
10 | //t.false(maxBy(args..), 'Expected');
11 | //t.throws(maxBy(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/merge/merge.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const merge = require('./merge.js');
3 |
4 | test('Testing merge', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof merge === 'function', 'merge is a Function');
8 | //t.deepEqual(merge(args..), 'Expected');
9 | //t.equal(merge(args..), 'Expected');
10 | //t.false(merge(args..), 'Expected');
11 | //t.throws(merge(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/minBy/minBy.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const minBy = require('./minBy.js');
3 |
4 | test('Testing minBy', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof minBy === 'function', 'minBy is a Function');
8 | //t.deepEqual(minBy(args..), 'Expected');
9 | //t.equal(minBy(args..), 'Expected');
10 | //t.false(minBy(args..), 'Expected');
11 | //t.throws(minBy(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/sleep/sleep.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const sleep = require('./sleep.js');
3 |
4 | test('Testing sleep', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof sleep === 'function', 'sleep is a Function');
8 | //t.deepEqual(sleep(args..), 'Expected');
9 | //t.equal(sleep(args..), 'Expected');
10 | //t.false(sleep(args..), 'Expected');
11 | //t.throws(sleep(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/sumBy/sumBy.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const sumBy = require('./sumBy.js');
3 |
4 | test('Testing sumBy', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof sumBy === 'function', 'sumBy is a Function');
8 | //t.deepEqual(sumBy(args..), 'Expected');
9 | //t.equal(sumBy(args..), 'Expected');
10 | //t.false(sumBy(args..), 'Expected');
11 | //t.throws(sumBy(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/snippets/sdbm.md:
--------------------------------------------------------------------------------
1 | ### sbdm
2 |
3 | Hashes the input string into a whole number.
4 |
5 | Use `String.split('')` and `Array.reduce()` to create a hash of the input string, utilizing bit shifting.
6 |
7 | ```js
8 | const sdbm = str => {
9 | let arr = str.split('');
10 | return arr.reduce(
11 | (hashCode, currentVal) =>
12 | (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode),
13 | 0
14 | );
15 | };
16 | ```
17 |
18 | ```js
19 | sdbm('name'); // -3521204949
20 | ```
21 |
--------------------------------------------------------------------------------
/snippets/countBy.zh.md:
--------------------------------------------------------------------------------
1 | ### countby
2 |
3 | 根据给定的函数对数组的元素进行分组,并返回每个组中元素的数量.
4 |
5 | 使用`array.map()`将数组的值映射到函数或属性name.use`array.reduce()`创建一个对象,其中的密钥是从映射的结果中产生的.
6 |
7 | ```js
8 | const countBy = (arr, fn) =>
9 | arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
10 | acc[val] = (acc[val] ƜƜ 0) + 1;
11 | return acc;
12 | }, {});
13 | ```
14 |
15 | ```js
16 | countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
17 | countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}
18 | ```
--------------------------------------------------------------------------------
/snippets/getURLParameters.zh.md:
--------------------------------------------------------------------------------
1 | ### geturlparameters
2 |
3 | 返回一个包含当前url参数的对象.
4 |
5 | 使用`string.match()`用适当的正则表达式来获得所有的键值对,`array.reduce()`将它们映射并组合成单个对象`location.search`作为适用于当前的理由`网址`.
6 |
7 | ```js
8 | const getURLParameters = url =>
9 | url
10 | .match(/([^?=&]+)(=([^&]*))/g)
11 | .reduce((a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), {});
12 | ```
13 |
14 | ```js
15 | getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'}
16 | ```
--------------------------------------------------------------------------------
/snippets/lowercaseKeys.zh.md:
--------------------------------------------------------------------------------
1 | ### lowercasekeys
2 |
3 | 从指定的对象创建一个新的对象,其中所有的键都是小写的.
4 |
5 | 使用`object.keys()`和`array.reduce()`从指定的对象创建一个新的对象. 将原始对象中的每个键转换为小写,使用`string.tolowercase()`.
6 |
7 | ```js
8 | const lowercaseKeys = obj =>
9 | Object.keys(obj).reduce((acc, key) => {
10 | acc[key.toLowerCase()] = obj[key];
11 | return acc;
12 | }, {});
13 | ```
14 |
15 | ```js
16 | const myObj = { Name: 'Adam', sUrnAME: 'Smith' };
17 | const myObjLower = lowercaseKeys(myObj); // {name: 'Adam', surname: 'Smith'};
18 | ```
--------------------------------------------------------------------------------
/snippets/nthElement.md:
--------------------------------------------------------------------------------
1 | ### nthElement
2 |
3 | Returns the nth element of an array.
4 |
5 | Use `Array.slice()` to get an array containing the nth element at the first place.
6 | If the index is out of bounds, return `[]`.
7 | Omit the second argument, `n`, to get the first element of the array.
8 |
9 | ```js
10 | const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
11 | ```
12 |
13 | ```js
14 | nthElement(['a', 'b', 'c'], 1); // 'b'
15 | nthElement(['a', 'b', 'b'], -3); // 'a'
16 | ```
17 |
--------------------------------------------------------------------------------
/test/README/README.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const README = require('./README.js');
3 |
4 | test('Testing README', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof README === 'function', 'README is a Function');
8 | //t.deepEqual(README(args..), 'Expected');
9 | //t.equal(README(args..), 'Expected');
10 | //t.false(README(args..), 'Expected');
11 | //t.throws(README(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/sample/sample.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const sample = require('./sample.js');
3 |
4 | test('Testing sample', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof sample === 'function', 'sample is a Function');
8 | //t.deepEqual(sample(args..), 'Expected');
9 | //t.equal(sample(args..), 'Expected');
10 | //t.false(sample(args..), 'Expected');
11 | //t.throws(sample(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/snippets/sumPower.zh.md:
--------------------------------------------------------------------------------
1 | ### sumpower
2 |
3 | 返回所有数字的幂的和`开始`至`结束`(包括两端).
4 |
5 | 使用`array.fill()`创建目标范围内所有数字的数组,`array.map()`和指数运算符(`**`)把他们提高到`功率`和`array.reduce()`把它们加在一起. 第二个参数,`功率`,使用默认的权力`2`. 第三个参数,`开始`,使用默认的起始值`1`.
6 |
7 | ```js
8 | const sumPower = (end, power = 2, start = 1) =>
9 | Array(end + 1 - start)
10 | .fill(0)
11 | .map((x, i) => (i + start) ** power)
12 | .reduce((a, b) => a + b, 0);
13 | ```
14 |
15 | ```js
16 | sumPower(10); // 385
17 | sumPower(10, 3); //3025
18 | sumPower(10, 3, 5); //2925
19 | ```
--------------------------------------------------------------------------------
/snippets/symmetricDifference.md:
--------------------------------------------------------------------------------
1 | ### symmetricDifference
2 |
3 | Returns the symmetric difference between two arrays.
4 |
5 | Create a `Set` from each array, then use `Array.filter()` on each of them to only keep values not contained in the other.
6 |
7 | ```js
8 | const symmetricDifference = (a, b) => {
9 | const sA = new Set(a),
10 | sB = new Set(b);
11 | return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];
12 | };
13 | ```
14 |
15 | ```js
16 | symmetricDifference([1, 2, 3], [1, 2, 4]); // [3,4]
17 | ```
18 |
--------------------------------------------------------------------------------
/test/collatz/collatz.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const collatz = require('./collatz.js');
3 |
4 | test('Testing collatz', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof collatz === 'function', 'collatz is a Function');
8 | //t.deepEqual(collatz(args..), 'Expected');
9 | //t.equal(collatz(args..), 'Expected');
10 | //t.false(collatz(args..), 'Expected');
11 | //t.throws(collatz(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/countBy/countBy.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const countBy = require('./countBy.js');
3 |
4 | test('Testing countBy', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof countBy === 'function', 'countBy is a Function');
8 | //t.deepEqual(countBy(args..), 'Expected');
9 | //t.equal(countBy(args..), 'Expected');
10 | //t.false(countBy(args..), 'Expected');
11 | //t.throws(countBy(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/factors/factors.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const factors = require('./factors.js');
3 |
4 | test('Testing factors', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof factors === 'function', 'factors is a Function');
8 | //t.deepEqual(factors(args..), 'Expected');
9 | //t.equal(factors(args..), 'Expected');
10 | //t.false(factors(args..), 'Expected');
11 | //t.throws(factors(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/httpGet/httpGet.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const httpGet = require('./httpGet.js');
3 |
4 | test('Testing httpGet', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof httpGet === 'function', 'httpGet is a Function');
8 | //t.deepEqual(httpGet(args..), 'Expected');
9 | //t.equal(httpGet(args..), 'Expected');
10 | //t.false(httpGet(args..), 'Expected');
11 | //t.throws(httpGet(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/httpPut/httpPut.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const httpPut = require('./httpPut.js');
3 |
4 | test('Testing httpPut', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof httpPut === 'function', 'httpPut is a Function');
8 | //t.deepEqual(httpPut(args..), 'Expected');
9 | //t.equal(httpPut(args..), 'Expected');
10 | //t.false(httpPut(args..), 'Expected');
11 | //t.throws(httpPut(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/mapKeys/mapKeys.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const mapKeys = require('./mapKeys.js');
3 |
4 | test('Testing mapKeys', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof mapKeys === 'function', 'mapKeys is a Function');
8 | //t.deepEqual(mapKeys(args..), 'Expected');
9 | //t.equal(mapKeys(args..), 'Expected');
10 | //t.false(mapKeys(args..), 'Expected');
11 | //t.throws(mapKeys(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/memoize/memoize.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const memoize = require('./memoize.js');
3 |
4 | test('Testing memoize', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof memoize === 'function', 'memoize is a Function');
8 | //t.deepEqual(memoize(args..), 'Expected');
9 | //t.equal(memoize(args..), 'Expected');
10 | //t.false(memoize(args..), 'Expected');
11 | //t.throws(memoize(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/shuffle/shuffle.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const shuffle = require('./shuffle.js');
3 |
4 | test('Testing shuffle', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof shuffle === 'function', 'shuffle is a Function');
8 | //t.deepEqual(shuffle(args..), 'Expected');
9 | //t.equal(shuffle(args..), 'Expected');
10 | //t.false(shuffle(args..), 'Expected');
11 | //t.throws(shuffle(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/snippets/isPrime.md:
--------------------------------------------------------------------------------
1 | ### isPrime
2 |
3 | Checks if the provided integer is a prime number.
4 |
5 | Check numbers from `2` to the square root of the given number.
6 | Return `false` if any of them divides the given number, else return `true`, unless the number is less than `2`.
7 |
8 | ```js
9 | const isPrime = num => {
10 | const boundary = Math.floor(Math.sqrt(num));
11 | for (var i = 2; i <= boundary; i++) if (num % i == 0) return false;
12 | return num >= 2;
13 | };
14 | ```
15 |
16 | ```js
17 | isPrime(11); // true
18 | ```
19 |
--------------------------------------------------------------------------------
/snippets/mapValues.zh.md:
--------------------------------------------------------------------------------
1 | ### mapvalues
2 |
3 | 使用与提供的对象相同的键创建对象,并通过为每个值运行提供的功能生成值.
4 |
5 | 使用`object.keys(OBJ)`遍历对象的keys.use`array.reduce()`使用相同的键和映射值创建一个新的对象`FN`.
6 |
7 | ```js
8 | const mapValues = (obj, fn) =>
9 | Object.keys(obj).reduce((acc, k) => {
10 | acc[k] = fn(obj[k], k, obj);
11 | return acc;
12 | }, {});
13 | ```
14 |
15 | ```js
16 | const users = {
17 | fred: { user: 'fred', age: 40 },
18 | pebbles: { user: 'pebbles', age: 1 }
19 | };
20 | mapValues(users, u => u.age); // { fred: 40, pebbles: 1 }
21 | ```
--------------------------------------------------------------------------------
/snippets/maxBy.md:
--------------------------------------------------------------------------------
1 | ### maxBy
2 |
3 | Returns the maximum value of an array, after mapping each element to a value using the provided function.
4 |
5 | Use `Array.map()` to map each element to the value returned by `fn`, `Math.max()` to get the maximum value.
6 |
7 | ```js
8 | const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
9 | ```
10 |
11 | ```js
12 | maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8
13 | maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/minBy.md:
--------------------------------------------------------------------------------
1 | ### minBy
2 |
3 | Returns the minimum value of an array, after mapping each element to a value using the provided function.
4 |
5 | Use `Array.map()` to map each element to the value returned by `fn`, `Math.min()` to get the maximum value.
6 |
7 | ```js
8 | const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
9 | ```
10 |
11 | ```js
12 | minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8
13 | minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8
14 | ```
15 |
--------------------------------------------------------------------------------
/snippets/truthCheckCollection.md:
--------------------------------------------------------------------------------
1 | ### truthCheckCollection
2 |
3 | Checks if the predicate (second argument) is truthy on all elements of a collection (first argument).
4 |
5 | Use `Array.every()` to check if each passed object has the specified property and if it returns a truthy value.
6 |
7 | ```js
8 | const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]);
9 | ```
10 |
11 | ```js
12 | truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true
13 | ```
14 |
--------------------------------------------------------------------------------
/snippets/UUIDGeneratorBrowser.md:
--------------------------------------------------------------------------------
1 | ### UUIDGeneratorBrowser
2 |
3 | Generates a UUID in a browser.
4 |
5 | Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4.
6 |
7 | ```js
8 | const UUIDGeneratorBrowser = () =>
9 | ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
10 | (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
11 | );
12 | ```
13 |
14 | ```js
15 | UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
16 | ```
17 |
--------------------------------------------------------------------------------
/snippets/flatten.zh.md:
--------------------------------------------------------------------------------
1 | ### 弄平
2 |
3 | 将阵列变平直到指定的深度.
4 |
5 | 使用递归,递减`深度`用于每个深度级别1`array.reduce()`和`array.concat()`合并元素或数组.base的情况下,为`深度`等于`1`停止递归. 第二个参数,`深度`只能将其平坦化`1`(单一平坦).
6 |
7 | ```js
8 | const flatten = (arr, depth = 1) =>
9 | depth != 1
10 | ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), [])
11 | : arr.reduce((a, v) => a.concat(v), []);
12 | ```
13 |
14 | ```js
15 | flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
16 | flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
17 | ```
--------------------------------------------------------------------------------
/snippets/forEachRight.md:
--------------------------------------------------------------------------------
1 | ### forEachRight
2 |
3 | Executes a provided function once for each array element, starting from the array's last element.
4 |
5 | Use `Array.slice(0)` to clone the given array, `Array.reverse()` to reverse it and `Array.forEach()` to iterate over the reversed array.
6 |
7 | ```js
8 | const forEachRight = (arr, callback) =>
9 | arr
10 | .slice(0)
11 | .reverse()
12 | .forEach(callback);
13 | ```
14 |
15 | ```js
16 | forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'
17 | ```
18 |
--------------------------------------------------------------------------------
/snippets/isValidJSON.md:
--------------------------------------------------------------------------------
1 | ### isValidJSON
2 |
3 | Checks if the provided argument is a valid JSON.
4 |
5 | Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON.
6 |
7 | ```js
8 | const isValidJSON = obj => {
9 | try {
10 | JSON.parse(obj);
11 | return true;
12 | } catch (e) {
13 | return false;
14 | }
15 | };
16 | ```
17 |
18 | ```js
19 | isValidJSON('{"name":"Adam","age":20}'); // true
20 | isValidJSON('{"name":"Adam",age:"20"}'); // false
21 | isValidJSON(null); // true
22 | ```
23 |
--------------------------------------------------------------------------------
/snippets/palindrome.zh.md:
--------------------------------------------------------------------------------
1 | ### 回文
2 |
3 | 回报`真正`如果给定的字符串是回文,`假`除此以外.
4 |
5 | 转换字符串`string.tolowercase()`并使用`与string.replace()`从中删除非字母数字字符. 然后,`string.split( '')`成个人角色,`array.reverse()`,`的string.join( '')`并在转换之后与原始的非反转字符串进行比较`string.tolowercase()`.
6 |
7 | ```js
8 | const palindrome = str => {
9 | const s = str.toLowerCase().replace(/[\W_]/g, '');
10 | return (
11 | s ===
12 | s
13 | .split('')
14 | .reverse()
15 | .join('')
16 | );
17 | };
18 | ```
19 |
20 | ```js
21 | palindrome('taco cat'); // true
22 | ```
--------------------------------------------------------------------------------
/snippets/select.zh.md:
--------------------------------------------------------------------------------
1 | ### 选择
2 |
3 | 从一个对象中检索给定选择器指定的一组属性.
4 |
5 | 使用`array.map()`对于每个选择器,`string.split( '')`分裂每个选择器和`array.reduce()`得到它所表示的价值.
6 |
7 | ```js
8 | const select = (from, ...selectors) =>
9 | [...selectors].map(s => s.split('.').reduce((prev, cur) => prev && prev[cur], from));
10 | ```
11 |
12 | ```js
13 | const obj = { selector: { to: { val: 'val to select' } } };
14 | select(obj, 'selector.to.val'); // ['val to select']
15 | select(obj, 'selector.to.val', 'selector.to'); // ['val to select', { val: 'val to select' }]
16 | ```
--------------------------------------------------------------------------------
/snippets/yesNo.md:
--------------------------------------------------------------------------------
1 | ### yesNo
2 |
3 | Returns `true` if the string is `y`/`yes` or `false` if the string is `n`/`no`.
4 |
5 | Use `RegExp.test()` to check if the string evaluates to `y/yes` or `n/no`.
6 | Omit the second argument, `def` to set the default answer as `no`.
7 |
8 | ```js
9 | const yesNo = (val, def = false) =>
10 | /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def;
11 | ```
12 |
13 | ```js
14 | yesNo('Y'); // true
15 | yesNo('yes'); // true
16 | yesNo('No'); // false
17 | yesNo('Foo', true); // true
18 | ```
19 |
--------------------------------------------------------------------------------
/test/colorize/colorize.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const colorize = require('./colorize.js');
3 |
4 | test('Testing colorize', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof colorize === 'function', 'colorize is a Function');
8 | //t.deepEqual(colorize(args..), 'Expected');
9 | //t.equal(colorize(args..), 'Expected');
10 | //t.false(colorize(args..), 'Expected');
11 | //t.throws(colorize(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/distance/distance.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const distance = require('./distance.js');
3 |
4 | test('Testing distance', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof distance === 'function', 'distance is a Function');
8 | //t.deepEqual(distance(args..), 'Expected');
9 | //t.equal(distance(args..), 'Expected');
10 | //t.false(distance(args..), 'Expected');
11 | //t.throws(distance(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/findLast/findLast.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const findLast = require('./findLast.js');
3 |
4 | test('Testing findLast', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof findLast === 'function', 'findLast is a Function');
8 | //t.deepEqual(findLast(args..), 'Expected');
9 | //t.equal(findLast(args..), 'Expected');
10 | //t.false(findLast(args..), 'Expected');
11 | //t.throws(findLast(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/getStyle/getStyle.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const getStyle = require('./getStyle.js');
3 |
4 | test('Testing getStyle', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof getStyle === 'function', 'getStyle is a Function');
8 | //t.deepEqual(getStyle(args..), 'Expected');
9 | //t.equal(getStyle(args..), 'Expected');
10 | //t.false(getStyle(args..), 'Expected');
11 | //t.throws(getStyle(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/hasClass/hasClass.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const hasClass = require('./hasClass.js');
3 |
4 | test('Testing hasClass', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof hasClass === 'function', 'hasClass is a Function');
8 | //t.deepEqual(hasClass(args..), 'Expected');
9 | //t.equal(hasClass(args..), 'Expected');
10 | //t.false(hasClass(args..), 'Expected');
11 | //t.throws(hasClass(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/hasFlags/hasFlags.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const hasFlags = require('./hasFlags.js');
3 |
4 | test('Testing hasFlags', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof hasFlags === 'function', 'hasFlags is a Function');
8 | //t.deepEqual(hasFlags(args..), 'Expected');
9 | //t.equal(hasFlags(args..), 'Expected');
10 | //t.false(hasFlags(args..), 'Expected');
11 | //t.throws(hasFlags(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/httpPost/httpPost.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const httpPost = require('./httpPost.js');
3 |
4 | test('Testing httpPost', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof httpPost === 'function', 'httpPost is a Function');
8 | //t.deepEqual(httpPost(args..), 'Expected');
9 | //t.equal(httpPost(args..), 'Expected');
10 | //t.false(httpPost(args..), 'Expected');
11 | //t.throws(httpPost(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/isEven/isEven.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const isEven = require('./isEven.js');
3 |
4 | test('Testing isEven', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof isEven === 'function', 'isEven is a Function');
8 | t.equal(isEven(4), true, '4 is even number');
9 | t.false(isEven(5), false, '5 is not an even number');
10 | //t.deepEqual(isEven(args..), 'Expected');
11 | //t.throws(isEven(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/redirect/redirect.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const redirect = require('./redirect.js');
3 |
4 | test('Testing redirect', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof redirect === 'function', 'redirect is a Function');
8 | //t.deepEqual(redirect(args..), 'Expected');
9 | //t.equal(redirect(args..), 'Expected');
10 | //t.false(redirect(args..), 'Expected');
11 | //t.throws(redirect(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/runAsync/runAsync.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const runAsync = require('./runAsync.js');
3 |
4 | test('Testing runAsync', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof runAsync === 'function', 'runAsync is a Function');
8 | //t.deepEqual(runAsync(args..), 'Expected');
9 | //t.equal(runAsync(args..), 'Expected');
10 | //t.false(runAsync(args..), 'Expected');
11 | //t.throws(runAsync(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/setStyle/setStyle.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const setStyle = require('./setStyle.js');
3 |
4 | test('Testing setStyle', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof setStyle === 'function', 'setStyle is a Function');
8 | //t.deepEqual(setStyle(args..), 'Expected');
9 | //t.equal(setStyle(args..), 'Expected');
10 | //t.false(setStyle(args..), 'Expected');
11 | //t.throws(setStyle(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------
/test/solveRPN/solveRPN.test.js:
--------------------------------------------------------------------------------
1 | const test = require('tape');
2 | const solveRPN = require('./solveRPN.js');
3 |
4 | test('Testing solveRPN', (t) => {
5 | //For more information on all the methods supported by tape
6 | //Please go to https://github.com/substack/tape
7 | t.true(typeof solveRPN === 'function', 'solveRPN is a Function');
8 | //t.deepEqual(solveRPN(args..), 'Expected');
9 | //t.equal(solveRPN(args..), 'Expected');
10 | //t.false(solveRPN(args..), 'Expected');
11 | //t.throws(solveRPN(args..), 'Expected');
12 | t.end();
13 | });
--------------------------------------------------------------------------------