diff --git a/.travis/push.sh b/.travis/push.sh index 38e97512b..174bb5311 100755 --- a/.travis/push.sh +++ b/.travis/push.sh @@ -1,6 +1,6 @@ setup_git() { - git config --global user.email "travis@travis-ci.org" - git config --global user.name "Travis CI" + git config --global user.email "30secondsofcode@gmail.com" + git config --global user.name "30secondsofcode" } commit_website_files() { diff --git a/README.md b/README.md index abd772b85..a5f5ca6d4 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![License](https://img.shields.io/badge/license-CC0--1.0-blue.svg)](https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE) [![Gitter chat](https://img.shields.io/badge/chat-on%20gitter-4FB999.svg)](https://gitter.im/30-seconds-of-code/Lobby) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Travis Build](https://travis-ci.org/Chalarangelo/30-seconds-of-code.svg?branch=master)](https://travis-ci.org/Chalarangelo/30-seconds-of-code) [![Insight.io](https://img.shields.io/badge/insight.io-Ready-brightgreen.svg)](https://insight.io/github.com/Chalarangelo/30-seconds-of-code/tree/master/?source=0) [![js-semistandard-style](https://img.shields.io/badge/code%20style-semistandard-brightgreen.svg)](https://github.com/Flet/semistandard) [![ProductHunt](https://img.shields.io/badge/producthunt-vote-orange.svg)](https://www.producthunt.com/posts/30-seconds-of-code) -> Curated collection of useful Javascript snippets that you can understand in 30 seconds or less. +> Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. - Use Ctrl + F or command + F to search for a snippet. @@ -13,7 +13,58 @@ - Snippets are written in ES6, use the [Babel transpiler](https://babeljs.io/) to ensure backwards-compatibility. - You can import these snippets into your text editor of choice (VSCode, Atom, Sublime) using the files found in [this repo](https://github.com/Rob-Rychs/30-seconds-of-code-texteditorsnippets). - You can import these snippets into Alfred 3, using [this file](https://github.com/lslvxy/30-seconds-of-code-alfredsnippets). -- You can find a package with all the snippets on [npm](https://www.npmjs.com/package/30-seconds-of-code). Bear in mind that most of these snippets are not production-ready. + +#### Package + +⚠️ **WARNING:** Snippets are not production ready. + +You can find a package with all the snippets on [npm](https://www.npmjs.com/package/30-seconds-of-code). + +``` +npm install 30-seconds-of-code +``` + +CDN links +- [ES2017 Full (UMD)](https://unpkg.com/30-seconds-of-code) +- [ES5 Minified (UMD)](https://unpkg.com/30-seconds-of-code/dist/_30s.es5.min.js) + +
+ +**Browser** + +> IMPORTANT: replace the `src` with the full version link and desired target spec (such as ES5 minified)): + +```html + + +``` + +**Node** + +```js +// CommonJS +const _30s = require('30-seconds-of-code'); +_30s.average(1, 2, 3); + +// ES Modules +import _30s from '30-seconds-of-code'; +_30s.average(1, 2, 3); +``` + +To import snippets directly: + +```js +// CommonJS +const { average } = require('30-seconds-of-code'); +average(1, 2, 3); + +// ES Modules +import { average } from '30-seconds-of-code'; +average(1, 2, 3); +``` +
## Table of Contents @@ -60,6 +111,8 @@ * [`join`](#join) * [`last`](#last) * [`mapObject`](#mapobject) +* [`maxN`](#maxn) +* [`minN`](#minn) * [`nthElement`](#nthelement) * [`pick`](#pick) * [`pull`](#pull) @@ -162,11 +215,14 @@ * [`distance`](#distance) * [`elo`](#elo) * [`factorial`](#factorial) +* [`factors`](#factors) * [`fibonacci`](#fibonacci) * [`fibonacciCountUntilNum`](#fibonaccicountuntilnum) * [`fibonacciUntilNum`](#fibonacciuntilnum) * [`gcd`](#gcd) +* [`geometricProgression`](#geometricprogression) * [`hammingDistance`](#hammingdistance) +* [`howManyTimes`](#howmanytimes) * [`inRange`](#inrange) * [`isArmstrongNumber`](#isarmstrongnumber) * [`isDivisible`](#isdivisible) @@ -237,6 +293,7 @@ * [`isAbsoluteURL`](#isabsoluteurl) * [`mask`](#mask) * [`palindrome`](#palindrome) +* [`pluralize`](#pluralize) * [`repeatString`](#repeatstring) * [`reverseString`](#reversestring) * [`sortCharactersInString`](#sortcharactersinstring) @@ -290,23 +347,24 @@
View contents -* [`geometricProgression`](#geometricprogression) +* [`maxN`](#maxn) +* [`minN`](#minn)
--- ## 🔌 Adapter -### call - -Given a key and a set of arguments, call them when given a context. Primarily useful in composition. - -Use a closure to call a stored key with stored arguments. - +### call + +Given a key and a set of arguments, call them when given a context. Primarily useful in composition. + +Use a closure to call a stored key with stored arguments. + ```js const call = (key, ...args) => context => context[key](...args); -``` - +``` +
Examples @@ -318,23 +376,23 @@ const map = call.bind(null, 'map'); Promise.resolve([1, 2, 3]) .then(map(x => 2 * x)) .then(console.log); //[ 2, 4, 6 ] -``` +```

[⬆ Back to top](#table-of-contents) -### collectInto - -Changes a function that accepts an array into a variadic function. - -Given a function, return a closure that collects all inputs into an array-accepting function. - +### collectInto + +Changes a function that accepts an array into a variadic function. + +Given a function, return a closure that collects all inputs into an array-accepting function. + ```js const collectInto = fn => (...args) => fn(args); -``` - +``` +
Examples @@ -344,23 +402,23 @@ let p1 = Promise.resolve(1); let p2 = Promise.resolve(2); let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3)); Pall(p1, p2, p3).then(console.log); -``` +```

[⬆ Back to top](#table-of-contents) -### flip - -Flip takes a function as an argument, then makes the first argument the last - -Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest. - +### flip + +Flip takes a function as an argument, then makes the first argument the last + +Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest. + ```js const flip = fn => (...args) => fn(args.pop(), ...args); -``` - +``` +
Examples @@ -372,7 +430,7 @@ let mergePerson = mergeFrom.bind(null, a); mergePerson(b); // == b b = {}; Object.assign(b, a); // == b -``` +```
@@ -434,16 +492,16 @@ delay(2000).then(() => console.log('Hi!')); // // Promise resolves after 2s
[⬆ Back to top](#table-of-contents) -### spreadOver - -Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function. - -Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function. - +### spreadOver + +Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function. + +Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function. + ```js const spreadOver = fn => argsArr => fn(...argsArr); -``` - +``` +
Examples @@ -451,7 +509,7 @@ const spreadOver = fn => argsArr => fn(...argsArr); const arrayMax = spreadOver(Math.max); arrayMax([1, 2, 3]); // 3 arrayMax([1, 2, 4]); // 4 -``` +```
@@ -1054,6 +1112,57 @@ squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
[⬆ Back to top](#table-of-contents) +### maxN + +Returns the `n` maximum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in descending order). + +Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order. +Use `Array.slice()` to get the specified number of elements. +Omit the second argument, `n`, to get a one-element array. + +```js +const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); +``` + +
+Examples + +```js +maxN([1, 2, 3]); // [3] +maxN([1, 2, 3], 2); // [3,2] +maxN([1, 2, 3], 4); // [3,2,1] +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + +### minN + +Returns the `n` minimum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in ascending order). + +Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in ascending order. +Use `Array.slice()` to get the specified number of elements. +Omit the second argument, `n`, to get a one-element array. + +```js +const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); +``` +
+Examples + +```js +minN([1, 2, 3]); // [1] +minN([1, 2, 3], 2); // [1,2] +minN([1, 2, 3], 4); // [1,2,3] +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### nthElement Returns the nth element of an array. @@ -2763,6 +2872,57 @@ factorial(6); // 720
[⬆ Back to top](#table-of-contents) +### factors + +Returns the array of factors of the given `num`. +If the second argument is set to `true` returns only the prime factors of `num`. +If `num` is `1` or `0` returns an empty array. +If `num` is less than `0` returns all the factors of `-int` together with their additive inverses. + +Use `Array.from()`, `Array.map()` and `Array.filter()` to find all the factors of `num`. +If given `num` is negative, use `Array.reduce()` to add the additive inverses to the array. +Return all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.filter()`. +Omit the second argument, `primes`, to return prime and non-prime factors by default. + +**Note**:- _Negative numbers are not considered prime._ + +```js +const factors = (num, primes = false) => { + const isPrime = num => { + const boundary = Math.floor(Math.sqrt(num)); + for (var i = 2; i <= boundary; i++) if (num % i === 0) return false; + return num >= 2; + }; + const isNeg = num < 0; + num = isNeg ? -num : num; + let array = Array.from({ length: num - 1 }) + .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false)) + .filter(val => val); + if (isNeg) + array = array.reduce((acc, val) => { + acc.push(val); + acc.push(-val); + return acc; + }, []); + return primes ? array.filter(isPrime) : array; +}; +``` + +
+Examples + +```js +factors(12); // [2,3,4,6,12] +factors(12, true); // [2,3] +factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12] +factors(-12, true); // [2,3] +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### fibonacci Generates an array, containing the Fibonacci sequence, up until the nth term. @@ -2871,6 +3031,37 @@ gcd(8, 36); // 4
[⬆ Back to top](#table-of-contents) +### geometricProgression + +Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`. +Returns an error if `step` equals `1`. + +Use `Array.from()`, `Math.log()` and `Math.floor()` to create an array of the desired length, `Array.map()` to fill with the desired values in a range. +Omit the second argument, `start`, to use a default value of `1`. +Omit the third argument, `step`, to use a default value of `2`. + +```js +const geometricProgression = (end, start = 1, step = 2) => + Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map( + (v, i) => start * step ** i + ); +``` + +
+Examples + +```js +geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256] +geometricProgression(256, 3); //[3, 6, 12, 24, 48, 96, 192] +geometricProgression(256, 1, 4); //[1, 4, 16, 64, 256] +geometricProgression(256, 2, 1); //Gives error +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### hammingDistance Calculates the Hamming distance between two values. @@ -2894,6 +3085,47 @@ hammingDistance(2, 3); // 1
[⬆ Back to top](#table-of-contents) +### howManyTimes + +Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer. +Works for both negative and positive integers. + +If `divisor` is `-1` or `1` return `Infinity`. +If `divisor` is `-0` or `0` return `0`. +Otherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer. +Return the number of times the loop was executed, `i`. + +```js +const howManyTimes = (num, divisor) => { + if (divisor === 1 || divisor === -1) return Infinity; + if (divisor === 0) return 0; + let i = 0; + while (Number.isInteger(num / divisor)) { + i++; + num = num / divisor; + } + return i; +}; +``` + +
+Examples + +```js +howManyTimes(100, 2); //2 +howManyTimes(100, -2); //2 +howManyTimes(100, 2.5); //2 +howManyTimes(100, 3); //0 +howManyTimes(100, 0); //0 +howManyTimes(100, 1); //Infinity +howManyTimes(100, -1); //Infinity +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### inRange Checks if the given number falls within the given range. @@ -4146,6 +4378,38 @@ palindrome('taco cat'); // true
[⬆ Back to top](#table-of-contents) +# pluralize + +If `num` is greater than `1` returns the plural form of the given string, else return the singular form. + +Check if `num` is greater than `0`. Throw an appropriate `Error` if not, return the appropriate string otherwise. +Omit the third argument, `items`, to use a default plural form same as `item` suffixed with a single `'s'`. + +```js +const pluralize = (num, item, items = item + 's') => + num <= 0 + ? (() => { + throw new Error(`'num' should be >= 1. Value povided was ${num}.`); + })() + : num === 1 ? item : items; +``` + +
+Examples + +```js +pluralize(1, 'apple', 'apples'); // 'apple' +pluralize(3, 'apple', 'apples'); // 'apples' +pluralize(2, 'apple'); // 'apples' +pluralize(0, 'apple', 'apples'); // Gives error +pluralize(-3, 'apple', 'apples'); // Gives error +``` + +
+ +
[⬆ Back to top](#table-of-contents) + + ### repeatString Repeats a string n times using `String.repeat()` @@ -5145,30 +5409,41 @@ yesNo('Foo', true); // true
[⬆ Back to top](#table-of-contents) ---- - ## _Uncategorized_ -### geometricProgression +### maxN -Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`. -Returns an error if `step` equals `1`. +Returns the `n` maximum elements from the provided array. If `n` is greater than or equal to the provided array's length than return the original array(sorted in descending order). -Use `Array.from()`, `Math.log()` and `Math.floor()` to create an array of the desired length, `Array.map()` to fill with the desired values in a range. -Omit the second argument, `start`, to use a default value of `1`. -Omit the third argument, `step`, to use a default value of `2`. +Sort's the array's shallow copy in descending order and returns the first n elements +Skip the second argument to get a single element(in the form of a array) ```js -const geometricProgression = (end, start = 1, step = 2) => - Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map( - (v, i) => start * step ** i - ); +const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); ``` ```js -geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256] -geometricProgression(256, 3); //[3, 6, 12, 24, 48, 96, 192] -geometricProgression(256, 1, 4); //[1, 4, 16, 64, 256] -geometricProgression(256, 2, 1); //Gives error +maxN([1, 2, 3]); // [3] +maxN([1, 2, 3], 2); // [3,2] +maxN([1, 2, 3], 4); // [3,2,1] +``` + +
[⬆ back to top](#table-of-contents) + + +### minN + +Returns the `n` minimum elements from the provided array. If `n` is greater than or equal to the provided array's length than return the original array(sorted in ascending order). + +Sort's the array's shallow copy in ascending order and returns the first n elements + +Skip the second argument to get a single element(in the form of a array) +```js +const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); +``` +```js +minN([1, 2, 3]); // [1] +minN([1, 2, 3], 2); // [1,2] +minN([1, 2, 3], 4); // [1,2,3] ```
[⬆ back to top](#table-of-contents) diff --git a/dist/_30s.es5.js b/dist/_30s.es5.js index 4b4436292..cf0644a3b 100644 --- a/dist/_30s.es5.js +++ b/dist/_30s.es5.js @@ -4,6 +4,33 @@ (global._30s = factory()); }(this, (function () { 'use strict'; +var JSONToDate = function JSONToDate(arr) { + var dt = new Date(parseInt(arr.toString().substr(6))); + return dt.getDate() + "/" + (dt.getMonth() + 1) + "/" + dt.getFullYear(); +}; + +var fs = typeof require !== "undefined" && require('fs'); +var JSONToFile = function JSONToFile(obj, filename) { + return fs.writeFile(filename + ".json", JSON.stringify(obj, null, 2)); +}; + +var RGBToHex = function RGBToHex(r, g, b) { + return ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); +}; + +var UUIDGeneratorBrowser = function UUIDGeneratorBrowser() { + return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function (c) { + return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16); + }); +}; + +var crypto$1 = typeof require !== "undefined" && require('crypto'); +var UUIDGeneratorNode = function UUIDGeneratorNode() { + return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function (c) { + return (c ^ crypto$1.randomBytes(1)[0] & 15 >> c / 4).toString(16); + }); +}; + var anagrams = function anagrams(str) { if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; return str.split('').reduce(function (acc, letter, i) { @@ -324,6 +351,30 @@ var factorial = function factorial(n) { }() : n <= 1 ? 1 : n * factorial(n - 1); }; +var factors = function factors(num) { + var primes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + var isPrime = function isPrime(num) { + var boundary = Math.floor(Math.sqrt(num)); + for (var i = 2; i <= boundary; i++) { + if (num % i === 0) return false; + }return num >= 2; + }; + var isNeg = num < 0; + num = isNeg ? -num : num; + var array = Array.from({ length: num - 1 }).map(function (val, i) { + return num % (i + 2) === 0 ? i + 2 : false; + }).filter(function (val) { + return val; + }); + if (isNeg) array = array.reduce(function (acc, val) { + acc.push(val); + acc.push(-val); + return acc; + }, []); + return primes ? array.filter(isPrime) : array; +}; + var fibonacci = function fibonacci(n) { return Array.from({ length: n }).reduce(function (acc, val, i) { return acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i); @@ -395,6 +446,14 @@ var gcd = function gcd() { }); }; +var geometricProgression = function geometricProgression(end) { + var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + var step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2; + return Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map(function (v, i) { + return start * Math.pow(step, i); + }); +}; + var getDaysDiffBetweenDates = function getDaysDiffBetweenDates(dateInitial, dateFinal) { return (dateFinal - dateInitial) / (1000 * 3600 * 24); }; @@ -474,10 +533,28 @@ var hide = function hide() { }); }; +var howManyTimes = function howManyTimes(num, divisor) { + if (divisor === 1 || divisor === -1) return Infinity; + if (divisor === 0) return 0; + var i = 0; + while (Number.isInteger(num / divisor)) { + i++; + num = num / divisor; + } + return i; +}; + var httpsRedirect = function httpsRedirect() { if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); }; +var inRange = function inRange(n, start) { + var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + if (end && start > end) end = [start, start = end][0]; + return end == null ? n >= 0 && n < start : n >= start && n < end; +}; + var initial = function initial(arr) { return arr.slice(0, -1); }; @@ -491,8 +568,9 @@ var initialize2DArray = function initialize2DArray(w, h) { var initializeArrayWithRange = function initializeArrayWithRange(end) { var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; - return Array.from({ length: end + 1 - start }).map(function (v, i) { - return i + start; + var step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1; + return Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(function (v, i) { + return i * step + start; }); }; @@ -501,13 +579,6 @@ var initializeArrayWithValues = function initializeArrayWithValues(n) { return Array(n).fill(value); }; -var inRange = function inRange(n, start) { - var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - - if (end && start > end) end = [start, start = end][0]; - return end == null ? n >= 0 && n < start : n >= start && n < end; -}; - var intersection = function intersection(a, b) { var s = new Set(b); return a.filter(function (x) { @@ -658,16 +729,6 @@ var join = function join(arr) { }, ''); }; -var JSONToDate = function JSONToDate(arr) { - var dt = new Date(parseInt(arr.toString().substr(6))); - return dt.getDate() + "/" + (dt.getMonth() + 1) + "/" + dt.getFullYear(); -}; - -var fs = typeof require !== "undefined" && require('fs'); -var JSONToFile = function JSONToFile(obj, filename) { - return fs.writeFile(filename + ".json", JSON.stringify(obj, null, 2)); -}; - var last = function last(arr) { return arr[arr.length - 1]; }; @@ -709,10 +770,11 @@ var mask = function mask(cc) { function _toConsumableArray$6(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } -var max = function max() { - var _ref; - - return Math.max.apply(Math, _toConsumableArray$6((_ref = []).concat.apply(_ref, arguments))); +var maxN = function maxN(arr) { + var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + return [].concat(_toConsumableArray$6(arr)).sort(function (a, b) { + return b - a; + }).slice(0, n); }; function _toConsumableArray$7(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } @@ -734,10 +796,11 @@ var memoize = function memoize(fn) { function _toConsumableArray$8(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } -var min = function min(arr) { - var _ref; - - return Math.min.apply(Math, _toConsumableArray$8((_ref = []).concat.apply(_ref, _toConsumableArray$8(arr)))); +var minN = function minN(arr) { + var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; + return [].concat(_toConsumableArray$8(arr)).sort(function (a, b) { + return a - b; + }).slice(0, n); }; var negate = function negate(func) { @@ -763,20 +826,6 @@ var objectToPairs = function objectToPairs(obj) { }); }; -var once = function once(fn) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return fn.apply(this, args); - }; -}; - var onUserInputChange = function onUserInputChange(callback) { var type = 'mouse', lastTime = 0; @@ -791,6 +840,20 @@ var onUserInputChange = function onUserInputChange(callback) { }); }; +var once = function once(fn) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + return fn.apply(this, args); + }; +}; + var _slicedToArray$2 = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); function _toConsumableArray$9(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } @@ -840,6 +903,13 @@ var pipeFunctions = function pipeFunctions() { }); }; +var pluralize = function pluralize(num, item) { + var items = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : item + 's'; + return num <= 0 ? function () { + throw new Error('\'num\' should be >= 1. Value povided was ' + num + '.'); + }() : num === 1 ? item : items; +}; + var powerset = function powerset(arr) { return arr.reduce(function (a, v) { return a.concat(a.map(function (r) { @@ -999,10 +1069,6 @@ var reverseString = function reverseString(str) { return str.split('').reverse().join(''); }; -var RGBToHex = function RGBToHex(r, g, b) { - return ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); -}; - var round = function round(n) { var decimals = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; return Number(Math.round(n + "e" + decimals) + "e-" + decimals); @@ -1279,20 +1345,12 @@ var toEnglishDate = function toEnglishDate(time) { } catch (e) {} }; -var toggleClass = function toggleClass(el, className) { - return el.classList.toggle(className); -}; - var toKebabCase = function toKebabCase(str) { return str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map(function (x) { return x.toLowerCase(); }).join('-'); }; -var tomorrow = function tomorrow() { - return new Date(new Date().getTime() + 86400000).toISOString().split('T')[0]; -}; - var toOrdinalSuffix = function toOrdinalSuffix(num) { var int = parseInt(num), digits = [int % 10, int % 100], @@ -1308,6 +1366,14 @@ var toSnakeCase = function toSnakeCase(str) { }).join('_'); }; +var toggleClass = function toggleClass(el, className) { + return el.classList.toggle(className); +}; + +var tomorrow = function tomorrow() { + return new Date(new Date().getTime() + 86400000).toISOString().split('T')[0]; +}; + var truncateString = function truncateString(str, num) { return str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; }; @@ -1340,19 +1406,6 @@ var untildify = function untildify(str) { return str.replace(/^~($|\/|\\)/, (typeof require !== "undefined" && require('os').homedir()) + "$1"); }; -var UUIDGeneratorBrowser = function UUIDGeneratorBrowser() { - return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function (c) { - return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16); - }); -}; - -var crypto$1 = typeof require !== "undefined" && require('crypto'); -var UUIDGeneratorNode = function UUIDGeneratorNode() { - return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function (c) { - return (c ^ crypto$1.randomBytes(1)[0] & 15 >> c / 4).toString(16); - }); -}; - var validateNumber = function validateNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; }; @@ -1401,7 +1454,7 @@ var zipObject = function zipObject(props, values) { }, {}); }; -var imports = { anagrams: anagrams, arrayToHtmlList: arrayToHtmlList, average: average, bottomVisible: bottomVisible, byteSize: byteSize, call: call, capitalize: capitalize, capitalizeEveryWord: capitalizeEveryWord, chainAsync: chainAsync, chunk: chunk, clampNumber: clampNumber, cleanObj: cleanObj, cloneRegExp: cloneRegExp, coalesce: coalesce, coalesceFactory: coalesceFactory, collatz: collatz, collectInto: collectInto, compact: compact, compose: compose, copyToClipboard: copyToClipboard, countOccurrences: countOccurrences, countVowels: countVowels, currentURL: currentURL, curry: curry, deepFlatten: deepFlatten, defer: defer, detectDeviceType: detectDeviceType, difference: difference, differenceWith: differenceWith, digitize: digitize, distance: distance, distinctValuesOfArray: distinctValuesOfArray, dropElements: dropElements, dropRight: dropRight, elementIsVisibleInViewport: elementIsVisibleInViewport, elo: elo, escapeHTML: escapeHTML, escapeRegExp: escapeRegExp, everyNth: everyNth, extendHex: extendHex, factorial: factorial, fibonacci: fibonacci, fibonacciCountUntilNum: fibonacciCountUntilNum, fibonacciUntilNum: fibonacciUntilNum, filterNonUnique: filterNonUnique, flatten: flatten, flattenDepth: flattenDepth, flip: flip, fromCamelCase: fromCamelCase, functionName: functionName, gcd: gcd, getDaysDiffBetweenDates: getDaysDiffBetweenDates, getScrollPosition: getScrollPosition, getStyle: getStyle, getType: getType, getURLParameters: getURLParameters, groupBy: groupBy, hammingDistance: hammingDistance, hasClass: hasClass, hasFlags: hasFlags, head: head, hexToRGB: hexToRGB, hide: hide, httpsRedirect: httpsRedirect, initial: initial, initialize2DArray: initialize2DArray, initializeArrayWithRange: initializeArrayWithRange, initializeArrayWithValues: initializeArrayWithValues, inRange: inRange, intersection: intersection, invertKeyValues: invertKeyValues, isAbsoluteURL: isAbsoluteURL, isArmstrongNumber: isArmstrongNumber, isArray: isArray, isArrayLike: isArrayLike, isBoolean: isBoolean, isDivisible: isDivisible, isEven: isEven, isFunction: isFunction, isNull: isNull, isNumber: isNumber, isPrime: isPrime, isPrimitive: isPrimitive, isPromiseLike: isPromiseLike, isSorted: isSorted, isString: isString, isSymbol: isSymbol, isTravisCI: isTravisCI, isValidJSON: isValidJSON, join: join, JSONToDate: JSONToDate, JSONToFile: JSONToFile, last: last, lcm: lcm, lowercaseKeys: lowercaseKeys, mapObject: mapObject, mask: mask, max: max, median: median, memoize: memoize, min: min, negate: negate, nthElement: nthElement, objectFromPairs: objectFromPairs, objectToPairs: objectToPairs, once: once, onUserInputChange: onUserInputChange, orderBy: orderBy, palindrome: palindrome, percentile: percentile, pick: pick, pipeFunctions: pipeFunctions, powerset: powerset, prettyBytes: prettyBytes, primes: primes, promisify: promisify, pull: pull, pullAtIndex: pullAtIndex, pullAtValue: pullAtValue, quickSort: quickSort, randomHexColorCode: randomHexColorCode, randomIntegerInRange: randomIntegerInRange, randomNumberInRange: randomNumberInRange, readFileLines: readFileLines, redirect: redirect, reducedFilter: reducedFilter, remove: remove, repeatString: repeatString, reverseString: reverseString, RGBToHex: RGBToHex, round: round, runAsync: runAsync, runPromisesInSeries: runPromisesInSeries, sample: sample, sampleSize: sampleSize, scrollToTop: scrollToTop, sdbm: sdbm, select: select, setStyle: setStyle, shallowClone: shallowClone, show: show, shuffle: shuffle, similarity: similarity, size: size, sleep: sleep, solveRPN: solveRPN, sortCharactersInString: sortCharactersInString, sortedIndex: sortedIndex, speechSynthesis: speechSynthesis, splitLines: splitLines, spreadOver: spreadOver, standardDeviation: standardDeviation, sum: sum, sumPower: sumPower, symmetricDifference: symmetricDifference, tail: tail, take: take, takeRight: takeRight, timeTaken: timeTaken, toCamelCase: toCamelCase, toDecimalMark: toDecimalMark, toEnglishDate: toEnglishDate, toggleClass: toggleClass, toKebabCase: toKebabCase, tomorrow: tomorrow, toOrdinalSuffix: toOrdinalSuffix, toSnakeCase: toSnakeCase, truncateString: truncateString, truthCheckCollection: truthCheckCollection, unescapeHTML: unescapeHTML, union: union, untildify: untildify, UUIDGeneratorBrowser: UUIDGeneratorBrowser, UUIDGeneratorNode: UUIDGeneratorNode, validateNumber: validateNumber, without: without, words: words, yesNo: yesNo, zip: zip, zipObject: zipObject }; +var imports = { JSONToDate: JSONToDate, JSONToFile: JSONToFile, RGBToHex: RGBToHex, UUIDGeneratorBrowser: UUIDGeneratorBrowser, UUIDGeneratorNode: UUIDGeneratorNode, anagrams: anagrams, arrayToHtmlList: arrayToHtmlList, average: average, bottomVisible: bottomVisible, byteSize: byteSize, call: call, capitalize: capitalize, capitalizeEveryWord: capitalizeEveryWord, chainAsync: chainAsync, chunk: chunk, clampNumber: clampNumber, cleanObj: cleanObj, cloneRegExp: cloneRegExp, coalesce: coalesce, coalesceFactory: coalesceFactory, collatz: collatz, collectInto: collectInto, compact: compact, compose: compose, copyToClipboard: copyToClipboard, countOccurrences: countOccurrences, countVowels: countVowels, currentURL: currentURL, curry: curry, deepFlatten: deepFlatten, defer: defer, detectDeviceType: detectDeviceType, difference: difference, differenceWith: differenceWith, digitize: digitize, distance: distance, distinctValuesOfArray: distinctValuesOfArray, dropElements: dropElements, dropRight: dropRight, elementIsVisibleInViewport: elementIsVisibleInViewport, elo: elo, escapeHTML: escapeHTML, escapeRegExp: escapeRegExp, everyNth: everyNth, extendHex: extendHex, factorial: factorial, factors: factors, fibonacci: fibonacci, fibonacciCountUntilNum: fibonacciCountUntilNum, fibonacciUntilNum: fibonacciUntilNum, filterNonUnique: filterNonUnique, flatten: flatten, flattenDepth: flattenDepth, flip: flip, fromCamelCase: fromCamelCase, functionName: functionName, gcd: gcd, geometricProgression: geometricProgression, getDaysDiffBetweenDates: getDaysDiffBetweenDates, getScrollPosition: getScrollPosition, getStyle: getStyle, getType: getType, getURLParameters: getURLParameters, groupBy: groupBy, hammingDistance: hammingDistance, hasClass: hasClass, hasFlags: hasFlags, head: head, hexToRGB: hexToRGB, hide: hide, howManyTimes: howManyTimes, httpsRedirect: httpsRedirect, inRange: inRange, initial: initial, initialize2DArray: initialize2DArray, initializeArrayWithRange: initializeArrayWithRange, initializeArrayWithValues: initializeArrayWithValues, intersection: intersection, invertKeyValues: invertKeyValues, isAbsoluteURL: isAbsoluteURL, isArmstrongNumber: isArmstrongNumber, isArray: isArray, isArrayLike: isArrayLike, isBoolean: isBoolean, isDivisible: isDivisible, isEven: isEven, isFunction: isFunction, isNull: isNull, isNumber: isNumber, isPrime: isPrime, isPrimitive: isPrimitive, isPromiseLike: isPromiseLike, isSorted: isSorted, isString: isString, isSymbol: isSymbol, isTravisCI: isTravisCI, isValidJSON: isValidJSON, join: join, last: last, lcm: lcm, lowercaseKeys: lowercaseKeys, mapObject: mapObject, mask: mask, maxN: maxN, median: median, memoize: memoize, minN: minN, negate: negate, nthElement: nthElement, objectFromPairs: objectFromPairs, objectToPairs: objectToPairs, onUserInputChange: onUserInputChange, once: once, orderBy: orderBy, palindrome: palindrome, percentile: percentile, pick: pick, pipeFunctions: pipeFunctions, pluralize: pluralize, powerset: powerset, prettyBytes: prettyBytes, primes: primes, promisify: promisify, pull: pull, pullAtIndex: pullAtIndex, pullAtValue: pullAtValue, quickSort: quickSort, randomHexColorCode: randomHexColorCode, randomIntegerInRange: randomIntegerInRange, randomNumberInRange: randomNumberInRange, readFileLines: readFileLines, redirect: redirect, reducedFilter: reducedFilter, remove: remove, repeatString: repeatString, reverseString: reverseString, round: round, runAsync: runAsync, runPromisesInSeries: runPromisesInSeries, sample: sample, sampleSize: sampleSize, scrollToTop: scrollToTop, sdbm: sdbm, select: select, setStyle: setStyle, shallowClone: shallowClone, show: show, shuffle: shuffle, similarity: similarity, size: size, sleep: sleep, solveRPN: solveRPN, sortCharactersInString: sortCharactersInString, sortedIndex: sortedIndex, speechSynthesis: speechSynthesis, splitLines: splitLines, spreadOver: spreadOver, standardDeviation: standardDeviation, sum: sum, sumPower: sumPower, symmetricDifference: symmetricDifference, tail: tail, take: take, takeRight: takeRight, timeTaken: timeTaken, toCamelCase: toCamelCase, toDecimalMark: toDecimalMark, toEnglishDate: toEnglishDate, toKebabCase: toKebabCase, toOrdinalSuffix: toOrdinalSuffix, toSnakeCase: toSnakeCase, toggleClass: toggleClass, tomorrow: tomorrow, truncateString: truncateString, truthCheckCollection: truthCheckCollection, unescapeHTML: unescapeHTML, union: union, untildify: untildify, validateNumber: validateNumber, without: without, words: words, yesNo: yesNo, zip: zip, zipObject: zipObject }; return imports; diff --git a/dist/_30s.es5.min.js b/dist/_30s.es5.min.js index 808d1c793..73b979232 100644 --- a/dist/_30s.es5.min.js +++ b/dist/_30s.es5.min.js @@ -1 +1 @@ -(function(a,b){'object'==typeof exports&&'undefined'!=typeof module?module.exports=b():'function'==typeof define&&define.amd?define(b):a._30s=b()})(this,function(){'use strict';function a(a){return Array.isArray(a)?a:Array.from(a)}function b(a){if(Array.isArray(a)){for(var b=0,c=Array(a.length);b=b.length?2===b.length?[b,b[1]+b[0]]:[b]:b.split('').reduce(function(c,d,e){return c.concat(a(b.slice(0,e)+b.slice(e+1)).map(function(a){return d+a}))},[])},arrayToHtmlList:function(a,b){return a.map(function(a){return document.querySelector('#'+b).innerHTML+='
  • '+a+'
  • '})},average:function(){var a,b=(a=[]).concat.apply(a,arguments);return b.reduce(function(a,b){return a+b},0)/b.length},bottomVisible:function(){return document.documentElement.clientHeight+window.scrollY>=(document.documentElement.scrollHeight||document.documentElement.clientHeight)},byteSize:function(a){return new Blob([a]).size},call:function(a){for(var b=arguments.length,c=Array(1'"]/g,function(a){return{"&":'&',"<":'<',">":'>',"'":''','"':'"'}[a]||a})},escapeRegExp:function(a){return a.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')},everyNth:function(a,b){return a.filter(function(a,c){return c%b==b-1})},extendHex:function(a){return'#'+a.slice(a.startsWith('#')?1:0).split('').map(function(a){return a+a}).join('')},factorial:function a(b){return 0>b?function(){throw new TypeError('Negative numbers are not allowed!')}():1>=b?1:b*a(b-1)},fibonacci:function(a){return Array.from({length:a}).reduce(function(a,b,c){return a.concat(1>>(b?24:16))+', '+((c&(b?16711680:65280))>>>(b?16:8))+', '+((c&(b?65280:255))>>>(b?8:0))+(b?', '+(255&c):'')+')'},hide:function(){for(var a=arguments.length,b=Array(a),c=0;cc&&(c=b),null==c?0<=a&&a=b&&aa[1]?-1:1,d=!0,e=!1;try{for(var f,g=a.entries()[Symbol.iterator]();!(d=(f=g.next()).done);d=!0){var h=f.value,j=D(h,2),k=j[0],i=j[1];if(k===a.length-1)return c;if(0<(i-a[k+1])*c)return 0}}catch(a){e=!0,b=a}finally{try{!d&&g.return&&g.return()}finally{if(e)throw b}}},isString:function(a){return'string'==typeof a},isSymbol:function(a){return'symbol'===('undefined'==typeof a?'undefined':E(a))},isTravisCI:function(){return'TRAVIS'in process.env&&'CI'in process.env},isValidJSON:function(a){try{return JSON.parse(a),!0}catch(a){return!1}},join:function(a){var b=1e-c&&(b='mouse',a(b),document.removeEventListener('mousemove',d)),c=e};document.addEventListener('touchstart',function(){'touch'==b||(b='touch',a(b),document.addEventListener('mousemove',d))})},orderBy:function(a,c,d){return[].concat(k(a)).sort(function(e,a){return c.reduce(function(b,c,f){if(0===b){var g=d&&'desc'===d[f]?[a[c],e[c]]:[e[c],a[c]],h=G(g,2),i=h[0],j=h[1];b=i>j?1:iMath.abs(a))return a+(c?' ':'')+d[0];var e=x(t(Math.log10(0>a?-a:a)/3),d.length-1),f=+((0>a?-a:a)/w(1e3,e)).toPrecision(b);return(0>a?'-':'')+f+(c?' ':'')+d[e]},primes:function(a){var b=Array.from({length:a-1}).map(function(a,b){return b+2}),c=t(u(a)),d=Array.from({length:c-1}).map(function(a,b){return b+2});return d.forEach(function(a){return b=b.filter(function(b){return 0!=b%a||b==a})}),b},promisify:function(a){return function(){for(var b=arguments.length,c=Array(b),d=0;de:a<=e}),c)),[e],l(a(f.filter(function(a){return c?a<=e:a>e}),c)))},randomHexColorCode:function(){var a=(0|1048575*Math.random()).toString(16);return'#'+(6===a.length?a:(0|15*Math.random()).toString(16)+a)},randomIntegerInRange:function(a,b){return t(Math.random()*(b-a+1))+a},randomNumberInRange:function(a,b){return Math.random()*(b-a)+a},readFileLines:function(a){return H.readFileSync(a).toString('UTF8').split('\n')},redirect:function(a){var b=1a[a.length-1],d=a.findIndex(function(a){return c?b>=a:b<=a});return-1===d?a.length:d},speechSynthesis:function(a){var b=new SpeechSynthesisUtterance(a);b.voice=window.speechSynthesis.getVoices()[0],window.speechSynthesis.speak(b)},splitLines:function(a){return a.split(/\r?\n/)},spreadOver:function(a){return function(b){return a.apply(void 0,p(b))}},standardDeviation:function(a){var b=1b?a.slice(0,3',"'":'\'',""":'"'}[a]||a})},union:function(c,a){return Array.from(new Set([].concat(r(c),r(a))))},untildify:function(a){return a.replace(/^~($|\/|\\)/,('undefined'!=typeof require&&require('os').homedir())+'$1')},UUIDGeneratorBrowser:function(){return'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,function(a){return(a^crypto.getRandomValues(new Uint8Array(1))[0]&15>>a/4).toString(16)})},UUIDGeneratorNode:function(){return'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,function(a){return(a^J.randomBytes(1)[0]&15>>a/4).toString(16)})},validateNumber:function(a){return!isNaN(parseFloat(a))&&isFinite(a)&&+a==a},without:function(a){for(var b=arguments.length,c=Array(1>a/4).toString(16)})},UUIDGeneratorNode:function(){return'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,function(a){return(a^B.randomBytes(1)[0]&15>>a/4).toString(16)})},anagrams:function a(b){return 2>=b.length?2===b.length?[b,b[1]+b[0]]:[b]:b.split('').reduce(function(c,d,e){return c.concat(a(b.slice(0,e)+b.slice(e+1)).map(function(a){return d+a}))},[])},arrayToHtmlList:function(a,b){return a.map(function(a){return document.querySelector('#'+b).innerHTML+='
  • '+a+'
  • '})},average:function(){var a,b=(a=[]).concat.apply(a,arguments);return b.reduce(function(a,b){return a+b},0)/b.length},bottomVisible:function(){return document.documentElement.clientHeight+window.scrollY>=(document.documentElement.scrollHeight||document.documentElement.clientHeight)},byteSize:function(a){return new Blob([a]).size},call:function(a){for(var b=arguments.length,c=Array(1'"]/g,function(a){return{"&":'&',"<":'<',">":'>',"'":''','"':'"'}[a]||a})},escapeRegExp:function(a){return a.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')},everyNth:function(a,b){return a.filter(function(a,c){return c%b==b-1})},extendHex:function(a){return'#'+a.slice(a.startsWith('#')?1:0).split('').map(function(a){return a+a}).join('')},factorial:function a(b){return 0>b?function(){throw new TypeError('Negative numbers are not allowed!')}():1>=b?1:b*a(b-1)},factors:function(a){var b=1a;a=c?-a:a;var d=Array.from({length:a-1}).map(function(b,c){return 0==a%(c+2)&&c+2}).filter(function(a){return a});return c&&(d=d.reduce(function(a,b){return a.push(b),a.push(-b),a},[])),b?d.filter(function(a){for(var b=u(v(a)),c=2;c<=b;c++)if(0==a%c)return!1;return 2<=a}):d},fibonacci:function(a){return Array.from({length:a}).reduce(function(a,b,c){return a.concat(1>>(b?24:16))+', '+((c&(b?16711680:65280))>>>(b?16:8))+', '+((c&(b?65280:255))>>>(b?8:0))+(b?', '+(255&c):'')+')'},hide:function(){for(var a=arguments.length,b=Array(a),c=0;cc&&(c=b),null==c?0<=a&&a=b&&aa[1]?-1:1,d=!0,e=!1;try{for(var f,g=a.entries()[Symbol.iterator]();!(d=(f=g.next()).done);d=!0){var h=f.value,j=F(h,2),k=j[0],i=j[1];if(k===a.length-1)return c;if(0<(i-a[k+1])*c)return 0}}catch(a){e=!0,b=a}finally{try{!d&&g.return&&g.return()}finally{if(e)throw b}}},isString:function(a){return'string'==typeof a},isSymbol:function(a){return'symbol'===('undefined'==typeof a?'undefined':G(a))},isTravisCI:function(){return'TRAVIS'in process.env&&'CI'in process.env},isValidJSON:function(a){try{return JSON.parse(a),!0}catch(a){return!1}},join:function(a){var b=1e-c&&(b='mouse',a(b),document.removeEventListener('mousemove',d)),c=e};document.addEventListener('touchstart',function(){'touch'==b||(b='touch',a(b),document.addEventListener('mousemove',d))})},once:function(a){var b=!1;return function(){if(!b){b=!0;for(var c=arguments.length,d=Array(c),e=0;ej?1:i=a?function(){throw new Error('\'num\' should be >= 1. Value povided was '+a+'.')}():1===a?b:c},powerset:function(a){return a.reduce(function(b,a){return b.concat(b.map(function(b){return[a].concat(b)}))},[[]])},prettyBytes:function(a){var b=1Math.abs(a))return a+(c?' ':'')+d[0];var e=x(u(Math.log10(0>a?-a:a)/3),d.length-1),f=+((0>a?-a:a)/w(1e3,e)).toPrecision(b);return(0>a?'-':'')+f+(c?' ':'')+d[e]},primes:function(a){var b=Array.from({length:a-1}).map(function(a,b){return b+2}),c=u(v(a)),d=Array.from({length:c-1}).map(function(a,b){return b+2});return d.forEach(function(a){return b=b.filter(function(b){return 0!=b%a||b==a})}),b},promisify:function(a){return function(){for(var b=arguments.length,c=Array(b),d=0;de:a<=e}),c)),[e],l(a(f.filter(function(a){return c?a<=e:a>e}),c)))},randomHexColorCode:function(){var a=(0|1048575*Math.random()).toString(16);return'#'+(6===a.length?a:(0|15*Math.random()).toString(16)+a)},randomIntegerInRange:function(a,b){return u(Math.random()*(b-a+1))+a},randomNumberInRange:function(a,b){return Math.random()*(b-a)+a},readFileLines:function(a){return I.readFileSync(a).toString('UTF8').split('\n')},redirect:function(a){var b=1a[a.length-1],d=a.findIndex(function(a){return c?b>=a:b<=a});return-1===d?a.length:d},speechSynthesis:function(a){var b=new SpeechSynthesisUtterance(a);b.voice=window.speechSynthesis.getVoices()[0],window.speechSynthesis.speak(b)},splitLines:function(a){return a.split(/\r?\n/)},spreadOver:function(a){return function(b){return a.apply(void 0,p(b))}},standardDeviation:function(a){var b=1b?a.slice(0,3',"'":'\'',""":'"'}[a]||a})},union:function(c,a){return Array.from(new Set([].concat(r(c),r(a))))},untildify:function(a){return a.replace(/^~($|\/|\\)/,('undefined'!=typeof require&&require('os').homedir())+'$1')},validateNumber:function(a){return!isNaN(parseFloat(a))&&isFinite(a)&&+a==a},without:function(a){for(var b=arguments.length,c=Array(1 { + const dt = new Date(parseInt(arr.toString().substr(6))); + return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; +}; + +const fs = typeof require !== "undefined" && require('fs'); +const JSONToFile = (obj, filename) => + fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); + +const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); + +const UUIDGeneratorBrowser = () => + ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => + (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16) + ); + +const crypto$1 = typeof require !== "undefined" && require('crypto'); +const UUIDGeneratorNode = () => + ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => + (c ^ (crypto$1.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16) + ); + const anagrams = str => { if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; return str @@ -171,6 +193,26 @@ const factorial = n => })() : n <= 1 ? 1 : n * factorial(n - 1); +const factors = (num, primes = false) => { + const isPrime = num => { + const boundary = Math.floor(Math.sqrt(num)); + for (var i = 2; i <= boundary; i++) if (num % i === 0) return false; + return num >= 2; + }; + const isNeg = num < 0; + num = isNeg ? -num : num; + let array = Array.from({ length: num - 1 }) + .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false)) + .filter(val => val); + if (isNeg) + array = array.reduce((acc, val) => { + acc.push(val); + acc.push(-val); + return acc; + }, []); + return primes ? array.filter(isPrime) : array; +}; + const fibonacci = n => Array.from({ length: n }).reduce( (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), @@ -213,6 +255,11 @@ const gcd = (...arr) => { return data.reduce((a, b) => helperGcd(a, b)); }; +const geometricProgression = (end, start = 1, step = 2) => + Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map( + (v, i) => start * step ** i + ); + const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); @@ -268,10 +315,26 @@ const hexToRGB = hex => { const hide = (...el) => [...el].forEach(e => (e.style.display = 'none')); +const howManyTimes = (num, divisor) => { + if (divisor === 1 || divisor === -1) return Infinity; + if (divisor === 0) return 0; + let i = 0; + while (Number.isInteger(num / divisor)) { + i++; + num = num / divisor; + } + return i; +}; + const httpsRedirect = () => { if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); }; +const inRange = (n, start, end = null) => { + if (end && start > end) end = [start, (start = end)][0]; + return end == null ? n >= 0 && n < start : n >= start && n < end; +}; + const initial = arr => arr.slice(0, -1); const initialize2DArray = (w, h, val = null) => @@ -279,16 +342,11 @@ const initialize2DArray = (w, h, val = null) => .fill() .map(() => Array(w).fill(val)); -const initializeArrayWithRange = (end, start = 0) => - Array.from({ length: end + 1 - start }).map((v, i) => i + start); +const initializeArrayWithRange = (end, start = 0, step = 1) => + Array.from({ length: Math.ceil((end + 1 - start) / step) }).map((v, i) => i * step + start); const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value); -const inRange = (n, start, end = null) => { - if (end && start > end) end = [start, (start = end)][0]; - return end == null ? n >= 0 && n < start : n >= start && n < end; -}; - const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); @@ -373,15 +431,6 @@ const join = (arr, separator = ',', end = separator) => '' ); -const JSONToDate = arr => { - const dt = new Date(parseInt(arr.toString().substr(6))); - return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; -}; - -const fs = typeof require !== "undefined" && require('fs'); -const JSONToFile = (obj, filename) => - fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); - const last = arr => arr[arr.length - 1]; const lcm = (...arr) => { @@ -403,7 +452,7 @@ const mapObject = (arr, fn) => const mask = (cc, num = 4, mask = '*') => ('' + cc).slice(0, -num).replace(/./g, mask) + ('' + cc).slice(-num); -const max = (...arr) => Math.max(...[].concat(...arr)); +const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); const median = arr => { const mid = Math.floor(arr.length / 2), @@ -416,7 +465,7 @@ const memoize = fn => { return value => cache[value] || (cache[value] = fn(value)); }; -const min = arr => Math.min(...[].concat(...arr)); +const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); const negate = func => (...args) => !func(...args); @@ -426,15 +475,6 @@ const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {}); const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); -const once = fn => { - let called = false; - return function(...args) { - if (called) return; - called = true; - return fn.apply(this, args); - }; -}; - const onUserInputChange = callback => { let type = 'mouse', lastTime = 0; @@ -450,6 +490,15 @@ const onUserInputChange = callback => { }); }; +const once = fn => { + let called = false; + return function(...args) { + if (called) return; + called = true; + return fn.apply(this, args); + }; +}; + const orderBy = (arr, props, orders) => [...arr].sort((a, b) => props.reduce((acc, prop, i) => { @@ -480,6 +529,13 @@ const pick = (obj, arr) => const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); +const pluralize = (num, item, items = item + 's') => + num <= 0 + ? (() => { + throw new Error(`'num' should be >= 1. Value povided was ${num}.`); + })() + : num === 1 ? item : items; + const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); const prettyBytes = (num, precision = 3, addSpace = true) => { @@ -583,8 +639,6 @@ const reverseString = str => .reverse() .join(''); -const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); - const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); const runAsync = fn => { @@ -773,8 +827,6 @@ const toEnglishDate = time => { } catch (e) {} }; -const toggleClass = (el, className) => el.classList.toggle(className); - const toKebabCase = str => str && str @@ -782,8 +834,6 @@ const toKebabCase = str => .map(x => x.toLowerCase()) .join('-'); -const tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0]; - const toOrdinalSuffix = num => { const int = parseInt(num), digits = [int % 10, int % 100], @@ -802,6 +852,10 @@ const toSnakeCase = str => .map(x => x.toLowerCase()) .join('_'); +const toggleClass = (el, className) => el.classList.toggle(className); + +const tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0]; + const truncateString = (str, num) => str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; @@ -824,17 +878,6 @@ const union = (a, b) => Array.from(new Set([...a, ...b])); const untildify = str => str.replace(/^~($|\/|\\)/, `${typeof require !== "undefined" && require('os').homedir()}$1`); -const UUIDGeneratorBrowser = () => - ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => - (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16) - ); - -const crypto$1 = typeof require !== "undefined" && require('crypto'); -const UUIDGeneratorNode = () => - ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => - (c ^ (crypto$1.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16) - ); - const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; const without = (arr, ...args) => arr.filter(v => !args.includes(v)); @@ -854,6 +897,6 @@ const zip = (...arrays) => { const zipObject = (props, values) => props.reduce((obj, prop, index) => (obj[prop] = values[index], obj), {}); -var imports = {anagrams,arrayToHtmlList,average,bottomVisible,byteSize,call,capitalize,capitalizeEveryWord,chainAsync,chunk,clampNumber,cleanObj,cloneRegExp,coalesce,coalesceFactory,collatz,collectInto,compact,compose,copyToClipboard,countOccurrences,countVowels,currentURL,curry,deepFlatten,defer,detectDeviceType,difference,differenceWith,digitize,distance,distinctValuesOfArray,dropElements,dropRight,elementIsVisibleInViewport,elo,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,fibonacciCountUntilNum,fibonacciUntilNum,filterNonUnique,flatten,flattenDepth,flip,fromCamelCase,functionName,gcd,getDaysDiffBetweenDates,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,head,hexToRGB,hide,httpsRedirect,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithValues,inRange,intersection,invertKeyValues,isAbsoluteURL,isArmstrongNumber,isArray,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isNull,isNumber,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isValidJSON,join,JSONToDate,JSONToFile,last,lcm,lowercaseKeys,mapObject,mask,max,median,memoize,min,negate,nthElement,objectFromPairs,objectToPairs,once,onUserInputChange,orderBy,palindrome,percentile,pick,pipeFunctions,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,quickSort,randomHexColorCode,randomIntegerInRange,randomNumberInRange,readFileLines,redirect,reducedFilter,remove,repeatString,reverseString,RGBToHex,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,select,setStyle,shallowClone,show,shuffle,similarity,size,sleep,solveRPN,sortCharactersInString,sortedIndex,speechSynthesis,splitLines,spreadOver,standardDeviation,sum,sumPower,symmetricDifference,tail,take,takeRight,timeTaken,toCamelCase,toDecimalMark,toEnglishDate,toggleClass,toKebabCase,tomorrow,toOrdinalSuffix,toSnakeCase,truncateString,truthCheckCollection,unescapeHTML,union,untildify,UUIDGeneratorBrowser,UUIDGeneratorNode,validateNumber,without,words,yesNo,zip,zipObject,} +var imports = {JSONToDate,JSONToFile,RGBToHex,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,average,bottomVisible,byteSize,call,capitalize,capitalizeEveryWord,chainAsync,chunk,clampNumber,cleanObj,cloneRegExp,coalesce,coalesceFactory,collatz,collectInto,compact,compose,copyToClipboard,countOccurrences,countVowels,currentURL,curry,deepFlatten,defer,detectDeviceType,difference,differenceWith,digitize,distance,distinctValuesOfArray,dropElements,dropRight,elementIsVisibleInViewport,elo,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,factors,fibonacci,fibonacciCountUntilNum,fibonacciUntilNum,filterNonUnique,flatten,flattenDepth,flip,fromCamelCase,functionName,gcd,geometricProgression,getDaysDiffBetweenDates,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,head,hexToRGB,hide,howManyTimes,httpsRedirect,inRange,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithValues,intersection,invertKeyValues,isAbsoluteURL,isArmstrongNumber,isArray,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isNull,isNumber,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isValidJSON,join,last,lcm,lowercaseKeys,mapObject,mask,maxN,median,memoize,minN,negate,nthElement,objectFromPairs,objectToPairs,onUserInputChange,once,orderBy,palindrome,percentile,pick,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,quickSort,randomHexColorCode,randomIntegerInRange,randomNumberInRange,readFileLines,redirect,reducedFilter,remove,repeatString,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,select,setStyle,shallowClone,show,shuffle,similarity,size,sleep,solveRPN,sortCharactersInString,sortedIndex,speechSynthesis,splitLines,spreadOver,standardDeviation,sum,sumPower,symmetricDifference,tail,take,takeRight,timeTaken,toCamelCase,toDecimalMark,toEnglishDate,toKebabCase,toOrdinalSuffix,toSnakeCase,toggleClass,tomorrow,truncateString,truthCheckCollection,unescapeHTML,union,untildify,validateNumber,without,words,yesNo,zip,zipObject,} export default imports; diff --git a/dist/_30s.js b/dist/_30s.js index e53943229..80e679a38 100644 --- a/dist/_30s.js +++ b/dist/_30s.js @@ -4,6 +4,28 @@ (global._30s = factory()); }(this, (function () { 'use strict'; +const JSONToDate = arr => { + const dt = new Date(parseInt(arr.toString().substr(6))); + return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; +}; + +const fs = typeof require !== "undefined" && require('fs'); +const JSONToFile = (obj, filename) => + fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); + +const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); + +const UUIDGeneratorBrowser = () => + ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => + (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16) + ); + +const crypto$1 = typeof require !== "undefined" && require('crypto'); +const UUIDGeneratorNode = () => + ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => + (c ^ (crypto$1.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16) + ); + const anagrams = str => { if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; return str @@ -177,6 +199,26 @@ const factorial = n => })() : n <= 1 ? 1 : n * factorial(n - 1); +const factors = (num, primes = false) => { + const isPrime = num => { + const boundary = Math.floor(Math.sqrt(num)); + for (var i = 2; i <= boundary; i++) if (num % i === 0) return false; + return num >= 2; + }; + const isNeg = num < 0; + num = isNeg ? -num : num; + let array = Array.from({ length: num - 1 }) + .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false)) + .filter(val => val); + if (isNeg) + array = array.reduce((acc, val) => { + acc.push(val); + acc.push(-val); + return acc; + }, []); + return primes ? array.filter(isPrime) : array; +}; + const fibonacci = n => Array.from({ length: n }).reduce( (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), @@ -219,6 +261,11 @@ const gcd = (...arr) => { return data.reduce((a, b) => helperGcd(a, b)); }; +const geometricProgression = (end, start = 1, step = 2) => + Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map( + (v, i) => start * step ** i + ); + const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); @@ -274,10 +321,26 @@ const hexToRGB = hex => { const hide = (...el) => [...el].forEach(e => (e.style.display = 'none')); +const howManyTimes = (num, divisor) => { + if (divisor === 1 || divisor === -1) return Infinity; + if (divisor === 0) return 0; + let i = 0; + while (Number.isInteger(num / divisor)) { + i++; + num = num / divisor; + } + return i; +}; + const httpsRedirect = () => { if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); }; +const inRange = (n, start, end = null) => { + if (end && start > end) end = [start, (start = end)][0]; + return end == null ? n >= 0 && n < start : n >= start && n < end; +}; + const initial = arr => arr.slice(0, -1); const initialize2DArray = (w, h, val = null) => @@ -285,16 +348,11 @@ const initialize2DArray = (w, h, val = null) => .fill() .map(() => Array(w).fill(val)); -const initializeArrayWithRange = (end, start = 0) => - Array.from({ length: end + 1 - start }).map((v, i) => i + start); +const initializeArrayWithRange = (end, start = 0, step = 1) => + Array.from({ length: Math.ceil((end + 1 - start) / step) }).map((v, i) => i * step + start); const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value); -const inRange = (n, start, end = null) => { - if (end && start > end) end = [start, (start = end)][0]; - return end == null ? n >= 0 && n < start : n >= start && n < end; -}; - const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); @@ -379,15 +437,6 @@ const join = (arr, separator = ',', end = separator) => '' ); -const JSONToDate = arr => { - const dt = new Date(parseInt(arr.toString().substr(6))); - return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; -}; - -const fs = typeof require !== "undefined" && require('fs'); -const JSONToFile = (obj, filename) => - fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); - const last = arr => arr[arr.length - 1]; const lcm = (...arr) => { @@ -409,7 +458,7 @@ const mapObject = (arr, fn) => const mask = (cc, num = 4, mask = '*') => ('' + cc).slice(0, -num).replace(/./g, mask) + ('' + cc).slice(-num); -const max = (...arr) => Math.max(...[].concat(...arr)); +const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); const median = arr => { const mid = Math.floor(arr.length / 2), @@ -422,7 +471,7 @@ const memoize = fn => { return value => cache[value] || (cache[value] = fn(value)); }; -const min = arr => Math.min(...[].concat(...arr)); +const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); const negate = func => (...args) => !func(...args); @@ -432,15 +481,6 @@ const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {}); const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); -const once = fn => { - let called = false; - return function(...args) { - if (called) return; - called = true; - return fn.apply(this, args); - }; -}; - const onUserInputChange = callback => { let type = 'mouse', lastTime = 0; @@ -456,6 +496,15 @@ const onUserInputChange = callback => { }); }; +const once = fn => { + let called = false; + return function(...args) { + if (called) return; + called = true; + return fn.apply(this, args); + }; +}; + const orderBy = (arr, props, orders) => [...arr].sort((a, b) => props.reduce((acc, prop, i) => { @@ -486,6 +535,13 @@ const pick = (obj, arr) => const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); +const pluralize = (num, item, items = item + 's') => + num <= 0 + ? (() => { + throw new Error(`'num' should be >= 1. Value povided was ${num}.`); + })() + : num === 1 ? item : items; + const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); const prettyBytes = (num, precision = 3, addSpace = true) => { @@ -589,8 +645,6 @@ const reverseString = str => .reverse() .join(''); -const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); - const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); const runAsync = fn => { @@ -779,8 +833,6 @@ const toEnglishDate = time => { } catch (e) {} }; -const toggleClass = (el, className) => el.classList.toggle(className); - const toKebabCase = str => str && str @@ -788,8 +840,6 @@ const toKebabCase = str => .map(x => x.toLowerCase()) .join('-'); -const tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0]; - const toOrdinalSuffix = num => { const int = parseInt(num), digits = [int % 10, int % 100], @@ -808,6 +858,10 @@ const toSnakeCase = str => .map(x => x.toLowerCase()) .join('_'); +const toggleClass = (el, className) => el.classList.toggle(className); + +const tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0]; + const truncateString = (str, num) => str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; @@ -830,17 +884,6 @@ const union = (a, b) => Array.from(new Set([...a, ...b])); const untildify = str => str.replace(/^~($|\/|\\)/, `${typeof require !== "undefined" && require('os').homedir()}$1`); -const UUIDGeneratorBrowser = () => - ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => - (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16) - ); - -const crypto$1 = typeof require !== "undefined" && require('crypto'); -const UUIDGeneratorNode = () => - ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => - (c ^ (crypto$1.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16) - ); - const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; const without = (arr, ...args) => arr.filter(v => !args.includes(v)); @@ -860,7 +903,7 @@ const zip = (...arrays) => { const zipObject = (props, values) => props.reduce((obj, prop, index) => (obj[prop] = values[index], obj), {}); -var imports = {anagrams,arrayToHtmlList,average,bottomVisible,byteSize,call,capitalize,capitalizeEveryWord,chainAsync,chunk,clampNumber,cleanObj,cloneRegExp,coalesce,coalesceFactory,collatz,collectInto,compact,compose,copyToClipboard,countOccurrences,countVowels,currentURL,curry,deepFlatten,defer,detectDeviceType,difference,differenceWith,digitize,distance,distinctValuesOfArray,dropElements,dropRight,elementIsVisibleInViewport,elo,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,fibonacciCountUntilNum,fibonacciUntilNum,filterNonUnique,flatten,flattenDepth,flip,fromCamelCase,functionName,gcd,getDaysDiffBetweenDates,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,head,hexToRGB,hide,httpsRedirect,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithValues,inRange,intersection,invertKeyValues,isAbsoluteURL,isArmstrongNumber,isArray,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isNull,isNumber,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isValidJSON,join,JSONToDate,JSONToFile,last,lcm,lowercaseKeys,mapObject,mask,max,median,memoize,min,negate,nthElement,objectFromPairs,objectToPairs,once,onUserInputChange,orderBy,palindrome,percentile,pick,pipeFunctions,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,quickSort,randomHexColorCode,randomIntegerInRange,randomNumberInRange,readFileLines,redirect,reducedFilter,remove,repeatString,reverseString,RGBToHex,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,select,setStyle,shallowClone,show,shuffle,similarity,size,sleep,solveRPN,sortCharactersInString,sortedIndex,speechSynthesis,splitLines,spreadOver,standardDeviation,sum,sumPower,symmetricDifference,tail,take,takeRight,timeTaken,toCamelCase,toDecimalMark,toEnglishDate,toggleClass,toKebabCase,tomorrow,toOrdinalSuffix,toSnakeCase,truncateString,truthCheckCollection,unescapeHTML,union,untildify,UUIDGeneratorBrowser,UUIDGeneratorNode,validateNumber,without,words,yesNo,zip,zipObject,} +var imports = {JSONToDate,JSONToFile,RGBToHex,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,average,bottomVisible,byteSize,call,capitalize,capitalizeEveryWord,chainAsync,chunk,clampNumber,cleanObj,cloneRegExp,coalesce,coalesceFactory,collatz,collectInto,compact,compose,copyToClipboard,countOccurrences,countVowels,currentURL,curry,deepFlatten,defer,detectDeviceType,difference,differenceWith,digitize,distance,distinctValuesOfArray,dropElements,dropRight,elementIsVisibleInViewport,elo,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,factors,fibonacci,fibonacciCountUntilNum,fibonacciUntilNum,filterNonUnique,flatten,flattenDepth,flip,fromCamelCase,functionName,gcd,geometricProgression,getDaysDiffBetweenDates,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,head,hexToRGB,hide,howManyTimes,httpsRedirect,inRange,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithValues,intersection,invertKeyValues,isAbsoluteURL,isArmstrongNumber,isArray,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isNull,isNumber,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isValidJSON,join,last,lcm,lowercaseKeys,mapObject,mask,maxN,median,memoize,minN,negate,nthElement,objectFromPairs,objectToPairs,onUserInputChange,once,orderBy,palindrome,percentile,pick,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,quickSort,randomHexColorCode,randomIntegerInRange,randomNumberInRange,readFileLines,redirect,reducedFilter,remove,repeatString,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,select,setStyle,shallowClone,show,shuffle,similarity,size,sleep,solveRPN,sortCharactersInString,sortedIndex,speechSynthesis,splitLines,spreadOver,standardDeviation,sum,sumPower,symmetricDifference,tail,take,takeRight,timeTaken,toCamelCase,toDecimalMark,toEnglishDate,toKebabCase,toOrdinalSuffix,toSnakeCase,toggleClass,tomorrow,truncateString,truthCheckCollection,unescapeHTML,union,untildify,validateNumber,without,words,yesNo,zip,zipObject,} return imports; diff --git a/dist/_30s.min.js b/dist/_30s.min.js index 53c87c5d9..e0f592e27 100644 --- a/dist/_30s.min.js +++ b/dist/_30s.min.js @@ -1,4 +1,4 @@ -(function(a,b){'object'==typeof exports&&'undefined'!=typeof module?module.exports=b():'function'==typeof define&&define.amd?define(b):a._30s=b()})(this,function(){'use strict';var a=Math.floor,b=Math.sqrt,c=Math.log,d=Math.min,e=Math.max,f=Math.ceil;const g=(a)=>2>=a.length?2===a.length?[a,a[1]+a[0]]:[a]:a.split('').reduce((b,c,d)=>b.concat(g(a.slice(0,d)+a.slice(d+1)).map((a)=>c+a)),[]),h=(a,b=[],c)=>(Object.keys(a).forEach((d)=>{d===c?h(a[d],b,c):!b.includes(d)&&delete a[d]}),a),i=(a,b=a.length,...c)=>b<=c.length?a(...c):i.bind(null,a,b,...c),j=(a)=>[].concat(...a.map((a)=>Array.isArray(a)?j(a):a)),k=(a)=>0>a?(()=>{throw new TypeError('Negative numbers are not allowed!')})():1>=a?1:a*k(a-1),l=(a,b=1)=>1==b?a.reduce((b,a)=>b.concat(a),[]):a.reduce((c,a)=>c.concat(Array.isArray(a)?l(a,b-1):a),[]),m=(...a)=>{let b=[].concat(...a);const c=(a,b)=>b?m(b,a%b):a;return b.reduce((d,a)=>c(d,a))},n='undefined'!=typeof require&&require('fs'),o=([a,...b],c)=>isNaN(a)?[]:[...o(b.filter((b)=>c?b>a:b<=a),c),a,...o(b.filter((b)=>c?b<=a:b>a),c)],p='undefined'!=typeof require&&require('fs'),q=()=>{const a=document.documentElement.scrollTop||document.body.scrollTop;0a.map((a)=>document.querySelector('#'+b).innerHTML+=`
  • ${a}
  • `),average:(...a)=>{const b=[].concat(...a);return b.reduce((a,b)=>a+b,0)/b.length},bottomVisible:()=>document.documentElement.clientHeight+window.scrollY>=(document.documentElement.scrollHeight||document.documentElement.clientHeight),byteSize:(a)=>new Blob([a]).size,call:(a,...b)=>(c)=>c[a](...b),capitalize:([a,...b],c=!1)=>a.toUpperCase()+(c?b.join('').toLowerCase():b.join('')),capitalizeEveryWord:(a)=>a.replace(/\b[a-z]/g,(a)=>a.toUpperCase()),chainAsync:(a)=>{let b=0;const c=()=>a[b++](c);c()},chunk:(a,b)=>Array.from({length:f(a.length/b)},(c,d)=>a.slice(d*b,d*b+b)),clampNumber:(c,f,a)=>e(d(c,e(f,a)),d(f,a)),cleanObj:h,cloneRegExp:(a)=>new RegExp(a.source,a.flags),coalesce:(...a)=>a.find((a)=>![void 0,null].includes(a)),coalesceFactory:(a)=>(...b)=>b.find(a),collatz:(a)=>0==a%2?a/2:3*a+1,collectInto:(a)=>(...b)=>a(b),compact:(a)=>a.filter(Boolean),compose:(...a)=>a.reduce((a,b)=>(...c)=>a(b(...c))),copyToClipboard:(a)=>{const b=document.createElement('textarea');b.value=a,b.setAttribute('readonly',''),b.style.position='absolute',b.style.left='-9999px',document.body.appendChild(b);const c=!!(0a.reduce((c,a)=>a===b?c+1:c+0,0),countVowels:(a)=>(a.match(/[aeiou]/gi)||[]).length,currentURL:()=>window.location.href,curry:i,deepFlatten:j,defer:(a,...b)=>setTimeout(a,1,...b),detectDeviceType:()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?'Mobile':'Desktop',difference:(c,a)=>{const b=new Set(a);return c.filter((a)=>!b.has(a))},differenceWith:(a,b,c)=>a.filter((d)=>!b.find((a)=>c(d,a))),digitize:(a)=>[...(''+a)].map((a)=>parseInt(a)),distance:(a,b,c,d)=>Math.hypot(c-a,d-b),distinctValuesOfArray:(a)=>[...new Set(a)],dropElements:(a,b)=>{for(;0a.slice(0,-b),elementIsVisibleInViewport:(a,b=!1)=>{const{top:c,left:d,bottom:e,right:f}=a.getBoundingClientRect(),{innerHeight:g,innerWidth:h}=window;return b?(0{const d=(a,b)=>1/(1+10**((b-a)/400)),e=(e,f)=>e+b*(f-d(f?c:a,f?a:c));return[e(c,1),e(a,0)]},escapeHTML:(a)=>a.replace(/[&<>'"]/g,(a)=>({"&":'&',"<":'<',">":'>',"'":''','"':'"'})[a]||a),escapeRegExp:(a)=>a.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'),everyNth:(a,b)=>a.filter((a,c)=>c%b==b-1),extendHex:(a)=>'#'+a.slice(a.startsWith('#')?1:0).split('').map((a)=>a+a).join(''),factorial:k,fibonacci:(a)=>Array.from({length:a}).reduce((a,b,c)=>a.concat(1f(c(2.23606797749979*a+1/2)/0.48121182505960347),fibonacciUntilNum:(a)=>{let b=f(c(2.23606797749979*a+1/2)/0.48121182505960347);return Array.from({length:b}).reduce((a,b,c)=>a.concat(1a.filter((b)=>a.indexOf(b)===a.lastIndexOf(b)),flatten:(a)=>[].concat(...a),flattenDepth:l,flip:(a)=>(...b)=>a(b.pop(),...b),fromCamelCase:(a,b='_')=>a.replace(/([a-z\d])([A-Z])/g,'$1'+b+'$2').replace(/([A-Z]+)([A-Z][a-z\d]+)/g,'$1'+b+'$2').toLowerCase(),functionName:(a)=>(console.debug(a.name),a),gcd:m,getDaysDiffBetweenDates:(a,b)=>(b-a)/86400000,getScrollPosition:(a=window)=>({x:a.pageXOffset===void 0?a.scrollLeft:a.pageXOffset,y:a.pageYOffset===void 0?a.scrollTop:a.pageYOffset}),getStyle:(a,b)=>getComputedStyle(a)[b],getType:(a)=>a===void 0?'undefined':null===a?'null':a.constructor.name.toLowerCase(),getURLParameters:(a)=>a.match(/([^?=&]+)(=([^&]*))/g).reduce((b,a)=>(b[a.slice(0,a.indexOf('='))]=a.slice(a.indexOf('=')+1),b),{}),groupBy:(a,b)=>a.map('function'==typeof b?b:(a)=>a[b]).reduce((b,c,d)=>(b[c]=(b[c]||[]).concat(a[d]),b),{}),hammingDistance:(a,b)=>((a^b).toString(2).match(/1/g)||'').length,hasClass:(a,b)=>a.classList.contains(b),hasFlags:(...a)=>a.every((a)=>process.argv.includes(/^-{1,2}/.test(a)?a:'--'+a)),head:(a)=>a[0],hexToRGB:(a)=>{let b=!1,c=a.slice(a.startsWith('#')?1:0);return 3===c.length?c=[...c].map((a)=>a+a).join(''):8===c.length&&(b=!0),c=parseInt(c,16),'rgb'+(b?'a':'')+'('+(c>>>(b?24:16))+', '+((c&(b?16711680:65280))>>>(b?16:8))+', '+((c&(b?65280:255))>>>(b?8:0))+(b?`, ${255&c}`:'')+')'},hide:(...a)=>[...a].forEach((a)=>a.style.display='none'),httpsRedirect:()=>{'https:'!==location.protocol&&location.replace('https://'+location.href.split('//')[1])},initial:(a)=>a.slice(0,-1),initialize2DArray:(a,b,c=null)=>Array(b).fill().map(()=>Array(a).fill(c)),initializeArrayWithRange:(a,b=0)=>Array.from({length:a+1-b}).map((a,c)=>c+b),initializeArrayWithValues:(a,b=0)=>Array(a).fill(b),inRange:(a,b,c=null)=>(c&&b>c&&(c=b),null==c?0<=a&&a=b&&a{const b=new Set(a);return c.filter((a)=>b.has(a))},invertKeyValues:(a)=>Object.keys(a).reduce((b,c)=>(b[a[c]]=c,b),{}),isAbsoluteURL:(a)=>/^[a-z][a-z0-9+.-]*:/.test(a),isArmstrongNumber:(a)=>((b)=>b.reduce((c,a)=>c+parseInt(a)**b.length,0)==a)((a+'').split('')),isArray:(a)=>!!a&&Array.isArray(a),isArrayLike:(a)=>{try{return[...a],!0}catch(a){return!1}},isBoolean:(a)=>'boolean'==typeof a,isDivisible:(a,b)=>0==a%b,isEven:(a)=>0==a%2,isFunction:(a)=>a&&'function'==typeof a,isNull:(a)=>null===a,isNumber:(a)=>'number'==typeof a,isPrime:(c)=>{const d=a(b(c));for(var e=2;e<=d;e++)if(0==c%e)return!1;return 2<=c},isPrimitive:(a)=>!['object','function'].includes(typeof a)||null===a,isPromiseLike:(a)=>null!==a&&('object'==typeof a||'function'==typeof a)&&'function'==typeof a.then,isSorted:(a)=>{const b=a[0]>a[1]?-1:1;for(let[c,d]of a.entries()){if(c===a.length-1)return b;if(0<(d-a[c+1])*b)return 0}},isString:(a)=>'string'==typeof a,isSymbol:(a)=>'symbol'==typeof a,isTravisCI:()=>'TRAVIS'in process.env&&'CI'in process.env,isValidJSON:(a)=>{try{return JSON.parse(a),!0}catch(a){return!1}},join:(a,b=',',c=b)=>a.reduce((d,e,f)=>f==a.length-2?d+e+c:f==a.length-1?d+e:d+e+b,''),JSONToDate:(a)=>{const b=new Date(parseInt(a.toString().substr(6)));return`${b.getDate()}/${b.getMonth()+1}/${b.getFullYear()}`},JSONToFile:(a,b)=>n.writeFile(`${b}.json`,JSON.stringify(a,null,2)),last:(a)=>a[a.length-1],lcm:(...a)=>{const b=(a,c)=>c?b(c,a%c):a,c=(a,c)=>a*c/b(a,c);return[].concat(...a).reduce((d,a)=>c(d,a))},lowercaseKeys:(a)=>Object.keys(a).reduce((b,c)=>(b[c.toLowerCase()]=a[c],b),{}),mapObject:(b,c)=>((d)=>(d=[b,b.map(c)],d[0].reduce((a,b,c)=>(a[b]=d[1][c],a),{})))(),mask:(a,b=4,c='*')=>(''+a).slice(0,-b).replace(/./g,c)+(''+a).slice(-b),max:(...a)=>e(...[].concat(...a)),median:(b)=>{const c=a(b.length/2),d=[...b].sort((c,a)=>c-a);return 0==b.length%2?(d[c-1]+d[c])/2:d[c]},memoize:(a)=>{const b=Object.create(null);return(c)=>b[c]||(b[c]=a(c))},min:(a)=>d(...[].concat(...a)),negate:(a)=>(...b)=>!a(...b),nthElement:(a,b=0)=>(0a.reduce((b,a)=>(b[a[0]]=a[1],b),{}),objectToPairs:(a)=>Object.keys(a).map((b)=>[b,a[b]]),once:(a)=>{let b=!1;return function(...c){if(!b)return b=!0,a.apply(this,c)}},onUserInputChange:(a)=>{let b='mouse',c=0;const d=()=>{const e=performance.now();20>e-c&&(b='mouse',a(b),document.removeEventListener('mousemove',d)),c=e};document.addEventListener('touchstart',()=>{'touch'==b||(b='touch',a(b),document.addEventListener('mousemove',d))})},orderBy:(a,c,d)=>[...a].sort((e,a)=>c.reduce((b,c,f)=>{if(0===b){const[g,h]=d&&'desc'===d[f]?[a[c],e[c]]:[e[c],a[c]];b=g>h?1:g{const b=a.toLowerCase().replace(/[\W_]/g,'');return b===b.split('').reverse().join('')},percentile:(a,b)=>100*a.reduce((a,c)=>a+(cb.reduce((b,c)=>(c in a&&(b[c]=a[c]),b),{}),pipeFunctions:(...a)=>a.reduce((a,b)=>(...c)=>b(a(...c))),powerset:(a)=>a.reduce((b,a)=>b.concat(b.map((b)=>[a].concat(b))),[[]]),prettyBytes:(b,c=3,e=!0)=>{const f=['B','KB','MB','GB','TB','PB','EB','ZB','YB'];if(1>Math.abs(b))return b+(e?' ':'')+f[0];const g=d(a(Math.log10(0>b?-b:b)/3),f.length-1),h=+((0>b?-b:b)/1e3**g).toPrecision(c);return(0>b?'-':'')+h+(e?' ':'')+f[g]},primes:(c)=>{let d=Array.from({length:c-1}).map((a,b)=>b+2),e=a(b(c)),f=Array.from({length:e-1}).map((a,b)=>b+2);return f.forEach((a)=>d=d.filter((b)=>0!=b%a||b==a)),d},promisify:(a)=>(...b)=>new Promise((c,d)=>a(...b,(a,b)=>a?d(a):c(b))),pull:(a,...b)=>{let c=Array.isArray(b[0])?b[0]:b,d=a.filter((a)=>!c.includes(a));a.length=0,d.forEach((b)=>a.push(b))},pullAtIndex:(a,b)=>{let c=[],d=a.map((a,d)=>b.includes(d)?c.push(a):a).filter((a,c)=>!b.includes(c));return a.length=0,d.forEach((b)=>a.push(b)),c},pullAtValue:(a,b)=>{let c=[],d=a.forEach((a)=>b.includes(a)?c.push(a):a),e=a.filter((a)=>!b.includes(a));return a.length=0,e.forEach((b)=>a.push(b)),c},quickSort:o,randomHexColorCode:()=>{let a=(0|1048575*Math.random()).toString(16);return'#'+(6===a.length?a:(0|15*Math.random()).toString(16)+a)},randomIntegerInRange:(b,c)=>a(Math.random()*(c-b+1))+b,randomNumberInRange:(a,b)=>Math.random()*(b-a)+a,readFileLines:(a)=>p.readFileSync(a).toString('UTF8').split('\n'),redirect:(a,b=!0)=>b?window.location.href=a:window.location.replace(a),reducedFilter:(a,b,c)=>a.filter(c).map((a)=>b.reduce((b,c)=>(b[c]=a[c],b),{})),remove:(a,b)=>Array.isArray(a)?a.filter(b).reduce((b,c)=>(a.splice(a.indexOf(c),1),b.concat(c)),[]):[],repeatString:(a='',b=2)=>0<=b?a.repeat(b):a,reverseString:(a)=>a.split('').reverse().join(''),RGBToHex:(a,c,d)=>((a<<16)+(c<<8)+d).toString(16).padStart(6,'0'),round:(a,b=0)=>+`${Math.round(`${a}e${b}`)}e-${b}`,runAsync:(a)=>{const b=` +(function(a,b){'object'==typeof exports&&'undefined'!=typeof module?module.exports=b():'function'==typeof define&&define.amd?define(b):a._30s=b()})(this,function(){'use strict';var a=Math.log,b=Math.floor,c=Math.sqrt,d=Math.min,e=Math.max,f=Math.ceil;const g='undefined'!=typeof require&&require('fs'),h='undefined'!=typeof require&&require('crypto'),j=(a)=>2>=a.length?2===a.length?[a,a[1]+a[0]]:[a]:a.split('').reduce((b,c,d)=>b.concat(j(a.slice(0,d)+a.slice(d+1)).map((a)=>c+a)),[]),i=(a,b=[],c)=>(Object.keys(a).forEach((d)=>{d===c?i(a[d],b,c):!b.includes(d)&&delete a[d]}),a),k=(a,b=a.length,...c)=>b<=c.length?a(...c):k.bind(null,a,b,...c),l=(a)=>[].concat(...a.map((a)=>Array.isArray(a)?l(a):a)),m=(a)=>0>a?(()=>{throw new TypeError('Negative numbers are not allowed!')})():1>=a?1:a*m(a-1),n=(a,b=1)=>1==b?a.reduce((b,a)=>b.concat(a),[]):a.reduce((c,a)=>c.concat(Array.isArray(a)?n(a,b-1):a),[]),o=(...a)=>{let b=[].concat(...a);const c=(a,b)=>b?o(b,a%b):a;return b.reduce((d,a)=>c(d,a))},p=([a,...b],c)=>isNaN(a)?[]:[...p(b.filter((b)=>c?b>a:b<=a),c),a,...p(b.filter((b)=>c?b<=a:b>a),c)],q='undefined'!=typeof require&&require('fs'),r=()=>{const a=document.documentElement.scrollTop||document.body.scrollTop;0{const b=new Date(parseInt(a.toString().substr(6)));return`${b.getDate()}/${b.getMonth()+1}/${b.getFullYear()}`},JSONToFile:(a,b)=>g.writeFile(`${b}.json`,JSON.stringify(a,null,2)),RGBToHex:(a,c,d)=>((a<<16)+(c<<8)+d).toString(16).padStart(6,'0'),UUIDGeneratorBrowser:()=>'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,(a)=>(a^crypto.getRandomValues(new Uint8Array(1))[0]&15>>a/4).toString(16)),UUIDGeneratorNode:()=>'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,(a)=>(a^h.randomBytes(1)[0]&15>>a/4).toString(16)),anagrams:j,arrayToHtmlList:(a,b)=>a.map((a)=>document.querySelector('#'+b).innerHTML+=`
  • ${a}
  • `),average:(...a)=>{const b=[].concat(...a);return b.reduce((a,b)=>a+b,0)/b.length},bottomVisible:()=>document.documentElement.clientHeight+window.scrollY>=(document.documentElement.scrollHeight||document.documentElement.clientHeight),byteSize:(a)=>new Blob([a]).size,call:(a,...b)=>(c)=>c[a](...b),capitalize:([a,...b],c=!1)=>a.toUpperCase()+(c?b.join('').toLowerCase():b.join('')),capitalizeEveryWord:(a)=>a.replace(/\b[a-z]/g,(a)=>a.toUpperCase()),chainAsync:(a)=>{let b=0;const c=()=>a[b++](c);c()},chunk:(a,b)=>Array.from({length:f(a.length/b)},(c,d)=>a.slice(d*b,d*b+b)),clampNumber:(c,f,a)=>e(d(c,e(f,a)),d(f,a)),cleanObj:i,cloneRegExp:(a)=>new RegExp(a.source,a.flags),coalesce:(...a)=>a.find((a)=>![void 0,null].includes(a)),coalesceFactory:(a)=>(...b)=>b.find(a),collatz:(a)=>0==a%2?a/2:3*a+1,collectInto:(a)=>(...b)=>a(b),compact:(a)=>a.filter(Boolean),compose:(...a)=>a.reduce((a,b)=>(...c)=>a(b(...c))),copyToClipboard:(a)=>{const b=document.createElement('textarea');b.value=a,b.setAttribute('readonly',''),b.style.position='absolute',b.style.left='-9999px',document.body.appendChild(b);const c=!!(0a.reduce((c,a)=>a===b?c+1:c+0,0),countVowels:(a)=>(a.match(/[aeiou]/gi)||[]).length,currentURL:()=>window.location.href,curry:k,deepFlatten:l,defer:(a,...b)=>setTimeout(a,1,...b),detectDeviceType:()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)?'Mobile':'Desktop',difference:(c,a)=>{const b=new Set(a);return c.filter((a)=>!b.has(a))},differenceWith:(a,b,c)=>a.filter((d)=>!b.find((a)=>c(d,a))),digitize:(a)=>[...(''+a)].map((a)=>parseInt(a)),distance:(a,b,c,d)=>Math.hypot(c-a,d-b),distinctValuesOfArray:(a)=>[...new Set(a)],dropElements:(a,b)=>{for(;0a.slice(0,-b),elementIsVisibleInViewport:(a,b=!1)=>{const{top:c,left:d,bottom:e,right:f}=a.getBoundingClientRect(),{innerHeight:g,innerWidth:h}=window;return b?(0{const d=(a,b)=>1/(1+10**((b-a)/400)),e=(e,f)=>e+b*(f-d(f?c:a,f?a:c));return[e(c,1),e(a,0)]},escapeHTML:(a)=>a.replace(/[&<>'"]/g,(a)=>({"&":'&',"<":'<',">":'>',"'":''','"':'"'})[a]||a),escapeRegExp:(a)=>a.replace(/[.*+?^${}()|[\]\\]/g,'\\$&'),everyNth:(a,b)=>a.filter((a,c)=>c%b==b-1),extendHex:(a)=>'#'+a.slice(a.startsWith('#')?1:0).split('').map((a)=>a+a).join(''),factorial:m,factors:(a,d=!1)=>{const e=0>a;a=e?-a:a;let f=Array.from({length:a-1}).map((b,c)=>0==a%(c+2)&&c+2).filter((a)=>a);return e&&(f=f.reduce((a,b)=>(a.push(b),a.push(-b),a),[])),d?f.filter((a)=>{const d=b(c(a));for(var e=2;e<=d;e++)if(0==a%e)return!1;return 2<=a}):f},fibonacci:(a)=>Array.from({length:a}).reduce((a,b,c)=>a.concat(1f(a(2.23606797749979*b+1/2)/0.48121182505960347),fibonacciUntilNum:(b)=>{let c=f(a(2.23606797749979*b+1/2)/0.48121182505960347);return Array.from({length:c}).reduce((a,b,c)=>a.concat(1a.filter((b)=>a.indexOf(b)===a.lastIndexOf(b)),flatten:(a)=>[].concat(...a),flattenDepth:n,flip:(a)=>(...b)=>a(b.pop(),...b),fromCamelCase:(a,b='_')=>a.replace(/([a-z\d])([A-Z])/g,'$1'+b+'$2').replace(/([A-Z]+)([A-Z][a-z\d]+)/g,'$1'+b+'$2').toLowerCase(),functionName:(a)=>(console.debug(a.name),a),gcd:o,geometricProgression:(c,d=1,e=2)=>Array.from({length:b(a(c/d)/a(e))+1}).map((a,b)=>d*e**b),getDaysDiffBetweenDates:(a,b)=>(b-a)/86400000,getScrollPosition:(a=window)=>({x:a.pageXOffset===void 0?a.scrollLeft:a.pageXOffset,y:a.pageYOffset===void 0?a.scrollTop:a.pageYOffset}),getStyle:(a,b)=>getComputedStyle(a)[b],getType:(a)=>a===void 0?'undefined':null===a?'null':a.constructor.name.toLowerCase(),getURLParameters:(a)=>a.match(/([^?=&]+)(=([^&]*))/g).reduce((b,a)=>(b[a.slice(0,a.indexOf('='))]=a.slice(a.indexOf('=')+1),b),{}),groupBy:(a,b)=>a.map('function'==typeof b?b:(a)=>a[b]).reduce((b,c,d)=>(b[c]=(b[c]||[]).concat(a[d]),b),{}),hammingDistance:(a,b)=>((a^b).toString(2).match(/1/g)||'').length,hasClass:(a,b)=>a.classList.contains(b),hasFlags:(...a)=>a.every((a)=>process.argv.includes(/^-{1,2}/.test(a)?a:'--'+a)),head:(a)=>a[0],hexToRGB:(a)=>{let b=!1,c=a.slice(a.startsWith('#')?1:0);return 3===c.length?c=[...c].map((a)=>a+a).join(''):8===c.length&&(b=!0),c=parseInt(c,16),'rgb'+(b?'a':'')+'('+(c>>>(b?24:16))+', '+((c&(b?16711680:65280))>>>(b?16:8))+', '+((c&(b?65280:255))>>>(b?8:0))+(b?`, ${255&c}`:'')+')'},hide:(...a)=>[...a].forEach((a)=>a.style.display='none'),howManyTimes:(a,b)=>{if(1===b||-1===b)return Infinity;if(0===b)return 0;let c=0;for(;Number.isInteger(a/b);)c++,a/=b;return c},httpsRedirect:()=>{'https:'!==location.protocol&&location.replace('https://'+location.href.split('//')[1])},inRange:(a,b,c=null)=>(c&&b>c&&(c=b),null==c?0<=a&&a=b&&aa.slice(0,-1),initialize2DArray:(a,b,c=null)=>Array(b).fill().map(()=>Array(a).fill(c)),initializeArrayWithRange:(a,b=0,c=1)=>Array.from({length:f((a+1-b)/c)}).map((a,d)=>d*c+b),initializeArrayWithValues:(a,b=0)=>Array(a).fill(b),intersection:(c,a)=>{const b=new Set(a);return c.filter((a)=>b.has(a))},invertKeyValues:(a)=>Object.keys(a).reduce((b,c)=>(b[a[c]]=c,b),{}),isAbsoluteURL:(a)=>/^[a-z][a-z0-9+.-]*:/.test(a),isArmstrongNumber:(a)=>((b)=>b.reduce((c,a)=>c+parseInt(a)**b.length,0)==a)((a+'').split('')),isArray:(a)=>!!a&&Array.isArray(a),isArrayLike:(a)=>{try{return[...a],!0}catch(a){return!1}},isBoolean:(a)=>'boolean'==typeof a,isDivisible:(a,b)=>0==a%b,isEven:(a)=>0==a%2,isFunction:(a)=>a&&'function'==typeof a,isNull:(a)=>null===a,isNumber:(a)=>'number'==typeof a,isPrime:(a)=>{const d=b(c(a));for(var e=2;e<=d;e++)if(0==a%e)return!1;return 2<=a},isPrimitive:(a)=>!['object','function'].includes(typeof a)||null===a,isPromiseLike:(a)=>null!==a&&('object'==typeof a||'function'==typeof a)&&'function'==typeof a.then,isSorted:(a)=>{const b=a[0]>a[1]?-1:1;for(let[c,d]of a.entries()){if(c===a.length-1)return b;if(0<(d-a[c+1])*b)return 0}},isString:(a)=>'string'==typeof a,isSymbol:(a)=>'symbol'==typeof a,isTravisCI:()=>'TRAVIS'in process.env&&'CI'in process.env,isValidJSON:(a)=>{try{return JSON.parse(a),!0}catch(a){return!1}},join:(a,b=',',c=b)=>a.reduce((d,e,f)=>f==a.length-2?d+e+c:f==a.length-1?d+e:d+e+b,''),last:(a)=>a[a.length-1],lcm:(...a)=>{const b=(a,c)=>c?b(c,a%c):a,c=(a,c)=>a*c/b(a,c);return[].concat(...a).reduce((d,a)=>c(d,a))},lowercaseKeys:(a)=>Object.keys(a).reduce((b,c)=>(b[c.toLowerCase()]=a[c],b),{}),mapObject:(b,c)=>((d)=>(d=[b,b.map(c)],d[0].reduce((a,b,c)=>(a[b]=d[1][c],a),{})))(),mask:(a,b=4,c='*')=>(''+a).slice(0,-b).replace(/./g,c)+(''+a).slice(-b),maxN:(a,b=1)=>[...a].sort((c,a)=>a-c).slice(0,b),median:(a)=>{const c=b(a.length/2),d=[...a].sort((c,a)=>c-a);return 0==a.length%2?(d[c-1]+d[c])/2:d[c]},memoize:(a)=>{const b=Object.create(null);return(c)=>b[c]||(b[c]=a(c))},minN:(a,b=1)=>[...a].sort((c,a)=>c-a).slice(0,b),negate:(a)=>(...b)=>!a(...b),nthElement:(a,b=0)=>(0a.reduce((b,a)=>(b[a[0]]=a[1],b),{}),objectToPairs:(a)=>Object.keys(a).map((b)=>[b,a[b]]),onUserInputChange:(a)=>{let b='mouse',c=0;const d=()=>{const e=performance.now();20>e-c&&(b='mouse',a(b),document.removeEventListener('mousemove',d)),c=e};document.addEventListener('touchstart',()=>{'touch'==b||(b='touch',a(b),document.addEventListener('mousemove',d))})},once:(a)=>{let b=!1;return function(...c){if(!b)return b=!0,a.apply(this,c)}},orderBy:(a,c,d)=>[...a].sort((e,a)=>c.reduce((b,c,f)=>{if(0===b){const[g,h]=d&&'desc'===d[f]?[a[c],e[c]]:[e[c],a[c]];b=g>h?1:g{const b=a.toLowerCase().replace(/[\W_]/g,'');return b===b.split('').reverse().join('')},percentile:(a,b)=>100*a.reduce((a,c)=>a+(cb.reduce((b,c)=>(c in a&&(b[c]=a[c]),b),{}),pipeFunctions:(...a)=>a.reduce((a,b)=>(...c)=>b(a(...c))),pluralize:(a,b,c=b+'s')=>0>=a?(()=>{throw new Error(`'num' should be >= 1. Value povided was ${a}.`)})():1===a?b:c,powerset:(a)=>a.reduce((b,a)=>b.concat(b.map((b)=>[a].concat(b))),[[]]),prettyBytes:(a,c=3,e=!0)=>{const f=['B','KB','MB','GB','TB','PB','EB','ZB','YB'];if(1>Math.abs(a))return a+(e?' ':'')+f[0];const g=d(b(Math.log10(0>a?-a:a)/3),f.length-1),h=+((0>a?-a:a)/1e3**g).toPrecision(c);return(0>a?'-':'')+h+(e?' ':'')+f[g]},primes:(a)=>{let d=Array.from({length:a-1}).map((a,b)=>b+2),e=b(c(a)),f=Array.from({length:e-1}).map((a,b)=>b+2);return f.forEach((a)=>d=d.filter((b)=>0!=b%a||b==a)),d},promisify:(a)=>(...b)=>new Promise((c,d)=>a(...b,(a,b)=>a?d(a):c(b))),pull:(a,...b)=>{let c=Array.isArray(b[0])?b[0]:b,d=a.filter((a)=>!c.includes(a));a.length=0,d.forEach((b)=>a.push(b))},pullAtIndex:(a,b)=>{let c=[],d=a.map((a,d)=>b.includes(d)?c.push(a):a).filter((a,c)=>!b.includes(c));return a.length=0,d.forEach((b)=>a.push(b)),c},pullAtValue:(a,b)=>{let c=[],d=a.forEach((a)=>b.includes(a)?c.push(a):a),e=a.filter((a)=>!b.includes(a));return a.length=0,e.forEach((b)=>a.push(b)),c},quickSort:p,randomHexColorCode:()=>{let a=(0|1048575*Math.random()).toString(16);return'#'+(6===a.length?a:(0|15*Math.random()).toString(16)+a)},randomIntegerInRange:(a,c)=>b(Math.random()*(c-a+1))+a,randomNumberInRange:(a,b)=>Math.random()*(b-a)+a,readFileLines:(a)=>q.readFileSync(a).toString('UTF8').split('\n'),redirect:(a,b=!0)=>b?window.location.href=a:window.location.replace(a),reducedFilter:(a,b,c)=>a.filter(c).map((a)=>b.reduce((b,c)=>(b[c]=a[c],b),{})),remove:(a,b)=>Array.isArray(a)?a.filter(b).reduce((b,c)=>(a.splice(a.indexOf(c),1),b.concat(c)),[]):[],repeatString:(a='',b=2)=>0<=b?a.repeat(b):a,reverseString:(a)=>a.split('').reverse().join(''),round:(a,b=0)=>+`${Math.round(`${a}e${b}`)}e-${b}`,runAsync:(a)=>{const b=` var fn = ${a.toString()}; this.postMessage(fn()); - `,c=new Worker(URL.createObjectURL(new Blob([b]),{type:'application/javascript; charset=utf-8'}));return new Promise((a,b)=>{c.onmessage=({data:b})=>{a(b),c.terminate()},c.onerror=(a)=>{b(a),c.terminate()}})},runPromisesInSeries:(a)=>a.reduce((a,b)=>a.then(b),Promise.resolve()),sample:(b)=>b[a(Math.random()*b.length)],sampleSize:([...b],c=1)=>{for(let d=b.length;d;){const c=a(Math.random()*d--);[b[d],b[c]]=[b[c],b[d]]}return b.slice(0,c)},scrollToTop:q,sdbm:(a)=>{let b=a.split('');return b.reduce((a,b)=>a=b.charCodeAt(0)+(a<<6)+(a<<16)-a,0)},select:(a,b)=>b.split('.').reduce((a,b)=>a&&a[b],a),setStyle:(a,b,c)=>a.style[b]=c,shallowClone:(a)=>Object.assign({},a),show:(...a)=>[...a].forEach((a)=>a.style.display=''),shuffle:([...b])=>{for(let c=b.length;c;){const d=a(Math.random()*c--);[b[c],b[d]]=[b[d],b[c]]}return b},similarity:(a,b)=>a.filter((a)=>b.includes(a)),size:(a)=>Array.isArray(a)?a.length:a&&'object'==typeof a?a.size||a.length||Object.keys(a).length:'string'==typeof a?new Blob([a]).size:0,sleep:(a)=>new Promise((b)=>setTimeout(b,a)),solveRPN:(a)=>{const c={"*":(c,a)=>c*a,"+":(c,a)=>c+a,"-":(c,a)=>c-a,"/":(c,a)=>c/a,"**":(c,a)=>c**a},[d,b]=[[],a.replace(/\^/g,'**').split(/\s+/g).filter((a)=>!/\s+/.test(a)&&''!==a)];if(b.forEach((e)=>{if(!isNaN(parseFloat(e))&&isFinite(e))d.push(e);else if(Object.keys(c).includes(e)){const[f,a]=[d.pop(),d.pop()];d.push(c[e](parseFloat(a),parseFloat(f)))}else throw`${e} is not a recognized symbol`}),1===d.length)return d.pop();throw`${a} is not a proper RPN. Please check it and try again`},sortCharactersInString:(a)=>a.split('').sort((c,a)=>c.localeCompare(a)).join(''),sortedIndex:(a,b)=>{const c=a[0]>a[a.length-1],d=a.findIndex((a)=>c?b>=a:b<=a);return-1===d?a.length:d},speechSynthesis:(a)=>{const b=new SpeechSynthesisUtterance(a);b.voice=window.speechSynthesis.getVoices()[0],window.speechSynthesis.speak(b)},splitLines:(a)=>a.split(/\r?\n/),spreadOver:(a)=>(b)=>a(...b),standardDeviation:(a,c=!1)=>{const d=a.reduce((a,b)=>a+b,0)/a.length;return b(a.reduce((a,b)=>a.concat((b-d)**2),[]).reduce((a,b)=>a+b,0)/(a.length-(c?0:1)))},sum:(...a)=>[].concat(...a).reduce((a,b)=>a+b,0),sumPower:(a,b=2,c=1)=>Array(a+1-c).fill(0).map((a,d)=>(d+c)**b).reduce((c,a)=>c+a,0),symmetricDifference:(c,a)=>{const b=new Set(c),d=new Set(a);return[...c.filter((a)=>!d.has(a)),...a.filter((a)=>!b.has(a))]},tail:(a)=>1a.slice(0,b),takeRight:(a,b=1)=>a.slice(a.length-b,a.length),timeTaken:(a)=>{console.time('timeTaken');const b=a();return console.timeEnd('timeTaken'),b},toCamelCase:(a)=>{let b=a&&a.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map((a)=>a.slice(0,1).toUpperCase()+a.slice(1).toLowerCase()).join('');return b.slice(0,1).toLowerCase()+b.slice(1)},toDecimalMark:(a)=>a.toLocaleString('en-US'),toEnglishDate:(a)=>{try{return new Date(a).toISOString().split('T')[0].replace(/-/g,'/')}catch(a){}},toggleClass:(a,b)=>a.classList.toggle(b),toKebabCase:(a)=>a&&a.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map((a)=>a.toLowerCase()).join('-'),tomorrow:()=>new Date(new Date().getTime()+8.64e7).toISOString().split('T')[0],toOrdinalSuffix:(a)=>{const b=parseInt(a),c=[b%10,b%100],d=['st','nd','rd','th'];return[1,2,3,4].includes(c[0])&&![11,12,13,14,15,16,17,18,19].includes(c[1])?b+d[c[0]-1]:b+d[3]},toSnakeCase:(a)=>a&&a.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map((a)=>a.toLowerCase()).join('_'),truncateString:(a,b)=>a.length>b?a.slice(0,3a.every((a)=>a[b]),unescapeHTML:(a)=>a.replace(/&|<|>|'|"/g,(a)=>({"&":'&',"<":'<',">":'>',"'":'\'',""":'"'})[a]||a),union:(c,a)=>Array.from(new Set([...c,...a])),untildify:(a)=>a.replace(/^~($|\/|\\)/,`${'undefined'!=typeof require&&require('os').homedir()}$1`),UUIDGeneratorBrowser:()=>'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,(a)=>(a^crypto.getRandomValues(new Uint8Array(1))[0]&15>>a/4).toString(16)),UUIDGeneratorNode:()=>'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,(a)=>(a^r.randomBytes(1)[0]&15>>a/4).toString(16)),validateNumber:(a)=>!isNaN(parseFloat(a))&&isFinite(a)&&+a==a,without:(a,...b)=>a.filter((a)=>!b.includes(a)),words:(a,b=/[^a-zA-Z-]+/)=>a.split(b).filter(Boolean),yesNo:(a,b=!1)=>!!/^(y|yes)$/i.test(a)||!/^(n|no)$/i.test(a)&&b,zip:(...a)=>{const b=e(...a.map((a)=>a.length));return Array.from({length:b}).map((b,c)=>Array.from({length:a.length},(b,d)=>a[d][c]))},zipObject:(a,b)=>a.reduce((a,c,d)=>(a[c]=b[d],a),{})}}); + `,c=new Worker(URL.createObjectURL(new Blob([b]),{type:'application/javascript; charset=utf-8'}));return new Promise((a,b)=>{c.onmessage=({data:b})=>{a(b),c.terminate()},c.onerror=(a)=>{b(a),c.terminate()}})},runPromisesInSeries:(a)=>a.reduce((a,b)=>a.then(b),Promise.resolve()),sample:(a)=>a[b(Math.random()*a.length)],sampleSize:([...a],c=1)=>{for(let d=a.length;d;){const c=b(Math.random()*d--);[a[d],a[c]]=[a[c],a[d]]}return a.slice(0,c)},scrollToTop:r,sdbm:(a)=>{let b=a.split('');return b.reduce((a,b)=>a=b.charCodeAt(0)+(a<<6)+(a<<16)-a,0)},select:(a,b)=>b.split('.').reduce((a,b)=>a&&a[b],a),setStyle:(a,b,c)=>a.style[b]=c,shallowClone:(a)=>Object.assign({},a),show:(...a)=>[...a].forEach((a)=>a.style.display=''),shuffle:([...a])=>{for(let c=a.length;c;){const d=b(Math.random()*c--);[a[c],a[d]]=[a[d],a[c]]}return a},similarity:(a,b)=>a.filter((a)=>b.includes(a)),size:(a)=>Array.isArray(a)?a.length:a&&'object'==typeof a?a.size||a.length||Object.keys(a).length:'string'==typeof a?new Blob([a]).size:0,sleep:(a)=>new Promise((b)=>setTimeout(b,a)),solveRPN:(a)=>{const c={"*":(c,a)=>c*a,"+":(c,a)=>c+a,"-":(c,a)=>c-a,"/":(c,a)=>c/a,"**":(c,a)=>c**a},[d,b]=[[],a.replace(/\^/g,'**').split(/\s+/g).filter((a)=>!/\s+/.test(a)&&''!==a)];if(b.forEach((e)=>{if(!isNaN(parseFloat(e))&&isFinite(e))d.push(e);else if(Object.keys(c).includes(e)){const[f,a]=[d.pop(),d.pop()];d.push(c[e](parseFloat(a),parseFloat(f)))}else throw`${e} is not a recognized symbol`}),1===d.length)return d.pop();throw`${a} is not a proper RPN. Please check it and try again`},sortCharactersInString:(a)=>a.split('').sort((c,a)=>c.localeCompare(a)).join(''),sortedIndex:(a,b)=>{const c=a[0]>a[a.length-1],d=a.findIndex((a)=>c?b>=a:b<=a);return-1===d?a.length:d},speechSynthesis:(a)=>{const b=new SpeechSynthesisUtterance(a);b.voice=window.speechSynthesis.getVoices()[0],window.speechSynthesis.speak(b)},splitLines:(a)=>a.split(/\r?\n/),spreadOver:(a)=>(b)=>a(...b),standardDeviation:(a,b=!1)=>{const d=a.reduce((a,b)=>a+b,0)/a.length;return c(a.reduce((a,b)=>a.concat((b-d)**2),[]).reduce((a,b)=>a+b,0)/(a.length-(b?0:1)))},sum:(...a)=>[].concat(...a).reduce((a,b)=>a+b,0),sumPower:(a,b=2,c=1)=>Array(a+1-c).fill(0).map((a,d)=>(d+c)**b).reduce((c,a)=>c+a,0),symmetricDifference:(c,a)=>{const b=new Set(c),d=new Set(a);return[...c.filter((a)=>!d.has(a)),...a.filter((a)=>!b.has(a))]},tail:(a)=>1a.slice(0,b),takeRight:(a,b=1)=>a.slice(a.length-b,a.length),timeTaken:(a)=>{console.time('timeTaken');const b=a();return console.timeEnd('timeTaken'),b},toCamelCase:(a)=>{let b=a&&a.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map((a)=>a.slice(0,1).toUpperCase()+a.slice(1).toLowerCase()).join('');return b.slice(0,1).toLowerCase()+b.slice(1)},toDecimalMark:(a)=>a.toLocaleString('en-US'),toEnglishDate:(a)=>{try{return new Date(a).toISOString().split('T')[0].replace(/-/g,'/')}catch(a){}},toKebabCase:(a)=>a&&a.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map((a)=>a.toLowerCase()).join('-'),toOrdinalSuffix:(a)=>{const b=parseInt(a),c=[b%10,b%100],d=['st','nd','rd','th'];return[1,2,3,4].includes(c[0])&&![11,12,13,14,15,16,17,18,19].includes(c[1])?b+d[c[0]-1]:b+d[3]},toSnakeCase:(a)=>a&&a.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map((a)=>a.toLowerCase()).join('_'),toggleClass:(a,b)=>a.classList.toggle(b),tomorrow:()=>new Date(new Date().getTime()+8.64e7).toISOString().split('T')[0],truncateString:(a,b)=>a.length>b?a.slice(0,3a.every((a)=>a[b]),unescapeHTML:(a)=>a.replace(/&|<|>|'|"/g,(a)=>({"&":'&',"<":'<',">":'>',"'":'\'',""":'"'})[a]||a),union:(c,a)=>Array.from(new Set([...c,...a])),untildify:(a)=>a.replace(/^~($|\/|\\)/,`${'undefined'!=typeof require&&require('os').homedir()}$1`),validateNumber:(a)=>!isNaN(parseFloat(a))&&isFinite(a)&&+a==a,without:(a,...b)=>a.filter((a)=>!b.includes(a)),words:(a,b=/[^a-zA-Z-]+/)=>a.split(b).filter(Boolean),yesNo:(a,b=!1)=>!!/^(y|yes)$/i.test(a)||!/^(n|no)$/i.test(a)&&b,zip:(...a)=>{const b=e(...a.map((a)=>a.length));return Array.from({length:b}).map((b,c)=>Array.from({length:a.length},(b,d)=>a[d][c]))},zipObject:(a,b)=>a.reduce((a,c,d)=>(a[c]=b[d],a),{})}}); diff --git a/docs/index.html b/docs/index.html index 7c981ee44..1ef56d4ff 100644 --- a/docs/index.html +++ b/docs/index.html @@ -59,7 +59,7 @@ wrapper.appendChild(box); box.appendChild(el); }); - }

     30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

     

    Adapter

    call

    Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

    Use a closure to call a stored key with stored arguments.

    const call = (key, ...args) => context => context[key](...args);
    +    }

     30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.

     

    Adapter

    call

    Given a key and a set of arguments, call them when given a context. Primarily useful in composition.

    Use a closure to call a stored key with stored arguments.

    const call = (key, ...args) => context => context[key](...args);
     
    Promise.resolve([1, 2, 3])
       .then(call('map', x => 2 * x))
       .then(console.log); //[ 2, 4, 6 ]
    @@ -194,6 +194,14 @@ join(['pen', 'pineapple', 'apple', 'pen']); //"pen,pineapple,apple,pen"
       ))();
     
    const squareIt = arr => mapObject(arr, a => a * a);
     squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }
    +

    maxN

    Returns the n maximum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in descending order).

    Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in descending order. Use Array.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.

    const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);
    +
    maxN([1, 2, 3]); // [3]
    +maxN([1, 2, 3], 2); // [3,2]
    +maxN([1, 2, 3], 4); // [3,2,1]
    +

    minN

    Returns the n minimum elements from the provided array. If n is greater than or equal to the provided array's length, then return the original array(sorted in ascending order).

    Use Array.sort() combined with the spread operator (...) to create a shallow clone of the array and sort it in ascending order. Use Array.slice() to get the specified number of elements. Omit the second argument, n, to get a one-element array.

    const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
    +
    minN([1, 2, 3]); // [1]
    +minN([1, 2, 3], 2); // [1,2]
    +minN([1, 2, 3], 4); // [1,2,3]
     

    nthElement

    Returns the nth element of an array.

    Use Array.slice() to get an array containing the nth element at the first place. If the index is out of bounds, return []. Omit the second argument, n, to get the first element of the array.

    const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0];
     
    nthElement(['a', 'b', 'c'], 1); // 'b'
     nthElement(['a', 'b', 'b'], -3); // 'a'
    @@ -603,6 +611,29 @@ elo([1200, 1200], 64); // [1232, 1168]
           })()
         : n <= 1 ? 1 : n * factorial(n - 1);
     
    factorial(6); // 720
    +

    factors

    Returns the array of factors of the given num. If the second argument is set to true returns only the prime factors of num. If num is 1 or 0 returns an empty array. If num is less than 0 returns all the factors of -int together with their additive inverses.

    Use Array.from(), Array.map() and Array.filter() to find all the factors of num. If given num is negative, use Array.reduce() to add the additive inverses to the array. Return all results if primes is false, else determine and return only the prime factors using isPrime and Array.filter(). Omit the second argument, primes, to return prime and non-prime factors by default.

    Note:- Negative numbers are not considered prime.

    const factors = (num, primes = false) => {
    +  const isPrime = num => {
    +    const boundary = Math.floor(Math.sqrt(num));
    +    for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
    +    return num >= 2;
    +  };
    +  const isNeg = num < 0;
    +  num = isNeg ? -num : num;
    +  let array = Array.from({ length: num - 1 })
    +    .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))
    +    .filter(val => val);
    +  if (isNeg)
    +    array = array.reduce((acc, val) => {
    +      acc.push(val);
    +      acc.push(-val);
    +      return acc;
    +    }, []);
    +  return primes ? array.filter(isPrime) : array;
    +};
    +
    factors(12); // [2,3,4,6,12]
    +factors(12, true); // [2,3]
    +factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]
    +factors(-12, true); // [2,3]
     

    fibonacci

    Generates an array, containing the Fibonacci sequence, up until the nth term.

    Create an empty array of the specific length, initializing the first two values (0 and 1). Use Array.reduce() to add values into the array, using the sum of the last two values, except for the first two.

    const fibonacci = n =>
       Array.from({ length: n }).reduce(
         (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
    @@ -626,8 +657,33 @@ elo([1200, 1200], 64); // [1232, 1168]
       return data.reduce((a, b) => helperGcd(a, b));
     };
     
    gcd(8, 36); // 4
    +

    geometricProgression

    Initializes an array containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step. Returns an error if step equals 1.

    Use Array.from(), Math.log() and Math.floor() to create an array of the desired length, Array.map() to fill with the desired values in a range. Omit the second argument, start, to use a default value of 1. Omit the third argument, step, to use a default value of 2.

    const geometricProgression = (end, start = 1, step = 2) =>
    +  Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map(
    +    (v, i) => start * step ** i
    +  );
    +
    geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256]
    +geometricProgression(256, 3); //[3, 6, 12, 24, 48, 96, 192]
    +geometricProgression(256, 1, 4); //[1, 4, 16, 64, 256]
    +geometricProgression(256, 2, 1); //Gives error
     

    hammingDistance

    Calculates the Hamming distance between two values.

    Use XOR operator (^) to find the bit difference between the two numbers, convert to a binary string using toString(2). Count and return the number of 1s in the string, using match(/1/g).

    const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length;
     
    hammingDistance(2, 3); // 1
    +

    howManyTimes

    Returns the number of times num can be divided by divisor (integer or fractional) without getting a fractional answer. Works for both negative and positive integers.

    If divisor is -1 or 1 return Infinity. If divisor is -0 or 0 return 0. Otherwise, keep dividing num with divisor and incrementing i, while the result is an integer. Return the number of times the loop was executed, i.

    const howManyTimes = (num, divisor) => {
    +  if (divisor === 1 || divisor === -1) return Infinity;
    +  if (divisor === 0) return 0;
    +  let i = 0;
    +  while (Number.isInteger(num / divisor)) {
    +    i++;
    +    num = num / divisor;
    +  }
    +  return i;
    +};
    +
    howManyTimes(100, 2); //2
    +howManyTimes(100, -2); //2
    +howManyTimes(100, 2.5); //2
    +howManyTimes(100, 3); //0
    +howManyTimes(100, 0); //0
    +howManyTimes(100, 1); //Infinity
    +howManyTimes(100, -1); //Infinity
     

    inRange

    Checks if the given number falls within the given range.

    Use arithmetic comparison to check if the given number is in the specified range. If the second parameter, end, is not specified, the range is considered to be from 0 to start.

    const inRange = (n, start, end = null) => {
       if (end && start > end) end = [start, (start = end)][0];
       return end == null ? n >= 0 && n < start : n >= start && n < end;
    @@ -916,6 +972,17 @@ mask(1234567890, -4, '$'); // '1234$$$$$$'
       );
     };
     
    palindrome('taco cat'); // true
    +

    pluralize

    If num is greater than 1 returns the plural form of the given string, else return the singular form.

    Check if num is greater than 0. Throw an appropriate Error if not, return the appropriate string otherwise. Omit the third argument, items, to use a default plural form same as item suffixed with a single 's'.

    const pluralize = (num, item, items = item + 's') =>
    +  num <= 0
    +    ? (() => {
    +        throw new Error(`'num' should be >= 1. Value povided was ${num}.`);
    +      })()
    +    : num === 1 ? item : items;
    +
    pluralize(1, 'apple', 'apples'); // 'apple'
    +pluralize(3, 'apple', 'apples'); // 'apples'
    +pluralize(2, 'apple'); // 'apples'
    +pluralize(0, 'apple', 'apples'); // Gives error
    +pluralize(-3, 'apple', 'apples'); // Gives error
     

    repeatString

    Repeats a string n times using String.repeat()

    If no string is provided the default is "" and the default number of times is 2.

    const repeatString = (str = '', num = 2) => {
       return num >= 0 ? str.repeat(num) : str;
     };
    @@ -1160,12 +1227,4 @@ console.log(sdbm('age')); // 808122783
     yesNo('yes'); // true
     yesNo('No'); // false
     yesNo('Foo', true); // true
    -

    Uncategorized

    geometricProgression

    Initializes an array containing the numbers in the specified range where start and end are inclusive and the ratio between two terms is step. Returns an error if step equals 1.

    Use Array.from(), Math.log() and Math.floor() to create an array of the desired length, Array.map() to fill with the desired values in a range. Omit the second argument, start, to use a default value of 1. Omit the third argument, step, to use a default value of 2.

    const geometricProgression = (end, start = 1, step = 2) =>
    -  Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map(
    -    (v, i) => start * step ** i
    -  );
    -
    geometricProgression(256); // [1, 2, 4, 8, 16, 32, 64, 128, 256]
    -geometricProgression(256, 3); //[3, 6, 12, 24, 48, 96, 192]
    -geometricProgression(256, 1, 4); //[1, 4, 16, 64, 256]
    -geometricProgression(256, 2, 1); //Gives error
     

    \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 07f08ceb1..2cd489a62 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1421,6 +1421,12 @@ "esutils": "2.0.2" } }, + "duplexer": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.1.tgz", + "integrity": "sha1-rOb/gIwc5mtX0ev5eXessCM0z8E=", + "dev": true + }, "ecc-jsbn": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz", @@ -3092,6 +3098,12 @@ "error-ex": "1.3.1" } }, + "parse-ms": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parse-ms/-/parse-ms-1.0.1.tgz", + "integrity": "sha1-VjRtR0nXjyNDDKDHE4UK75GqNh0=", + "dev": true + }, "path-exists": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz", @@ -3190,6 +3202,12 @@ "find-up": "1.1.2" } }, + "plur": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/plur/-/plur-1.0.0.tgz", + "integrity": "sha1-24XGgU9eXlo7Se/CjWBP7GKXUVY=", + "dev": true + }, "pluralize": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-1.2.1.tgz", @@ -3235,6 +3253,12 @@ "resolved": "https://registry.npmjs.org/qs/-/qs-6.3.2.tgz", "integrity": "sha1-51vV9uJoEioqDgvaYwslUMFmUCw=" }, + "re-emitter": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/re-emitter/-/re-emitter-1.1.3.tgz", + "integrity": "sha1-+p4xn/3u6zWycpbvDz03TawvUqc=", + "dev": true + }, "read-pkg": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-1.1.0.tgz", @@ -3387,6 +3411,12 @@ "resolved": "https://registry.npmjs.org/relateurl/-/relateurl-0.2.7.tgz", "integrity": "sha1-VNvzd+UUQKypCkzSdGANP/LYiKk=" }, + "repeat-string": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/repeat-string/-/repeat-string-1.6.1.tgz", + "integrity": "sha1-jcrkcOHIirwtYA//Sndihtp15jc=", + "dev": true + }, "repeating": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/repeating/-/repeating-2.0.1.tgz", @@ -3655,6 +3685,15 @@ "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz", "integrity": "sha1-yd96NCRZSt5r0RkA1ZZpbcBrrFc=" }, + "split": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/split/-/split-1.0.1.tgz", + "integrity": "sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg==", + "dev": true, + "requires": { + "through": "2.3.8" + } + }, "sprintf-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", @@ -3831,6 +3870,55 @@ } } }, + "tap-out": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/tap-out/-/tap-out-1.4.2.tgz", + "integrity": "sha1-yQfsG/lAURHQiCY+kvVgi4jLs3o=", + "dev": true, + "requires": { + "re-emitter": "1.1.3", + "readable-stream": "2.3.3", + "split": "1.0.1", + "trim": "0.0.1" + } + }, + "tap-spec": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/tap-spec/-/tap-spec-4.1.1.tgz", + "integrity": "sha1-4unyb1IIIysfViKIyXYk1YqI8Fo=", + "dev": true, + "requires": { + "chalk": "1.1.3", + "duplexer": "0.1.1", + "figures": "1.7.0", + "lodash": "3.10.1", + "pretty-ms": "2.1.0", + "repeat-string": "1.6.1", + "tap-out": "1.4.2", + "through2": "2.0.3" + }, + "dependencies": { + "chalk": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-1.1.3.tgz", + "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", + "dev": true, + "requires": { + "ansi-styles": "2.2.1", + "escape-string-regexp": "1.0.5", + "has-ansi": "2.0.0", + "strip-ansi": "3.0.1", + "supports-color": "2.0.0" + } + }, + "lodash": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-3.10.1.tgz", + "integrity": "sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y=", + "dev": true + } + } + }, "tape": { "version": "4.8.0", "resolved": "https://registry.npmjs.org/tape/-/tape-4.8.0.tgz", @@ -3894,6 +3982,12 @@ "punycode": "1.4.1" } }, + "trim": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/trim/-/trim-0.0.1.tgz", + "integrity": "sha1-WFhUf2spB1fulczMZm+1AITEYN0=", + "dev": true + }, "trim-newlines": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/trim-newlines/-/trim-newlines-1.0.0.tgz", diff --git a/package.json b/package.json index 0d0c380c0..1d58fac2b 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,8 @@ "rollup-plugin-babel": "^3.0.3", "rollup-plugin-babel-minify": "^3.1.2", "semistandard": "^11.0.0", - "tape": "^4.8.0" + "tape": "^4.8.0", + "tap-spec": "^4.1.1" }, "name": "30-seconds-of-code", "description": "A collection of useful JavaScript snippets.", @@ -24,7 +25,8 @@ "tagger": "node ./scripts/tag.js", "webber": "node ./scripts/web.js", "tdd": "node ./scripts/tdd.js", - "module": "node ./scripts/module.js" + "module": "node ./scripts/module.js", + "test": "tape test/**/*.test.js | tap-spec" }, "repository": { "type": "git", diff --git a/scripts/tdd.js b/scripts/tdd.js index d67396d7b..92cadd062 100644 --- a/scripts/tdd.js +++ b/scripts/tdd.js @@ -1,50 +1,84 @@ -const fs = require('fs-extra'); +/* + This is the tdd script that creates & updates your TDD environment . + Run using `npm run tagger`. +*/ +// Load modules +const fs = require('fs-extra'); +const chalk = require('chalk'); +// Load helper functions (these are from existing snippets in 30 seconds of code!) +const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; +if(isTravisCI() && process.env['TRAVIS_EVENT_TYPE'] !== 'cron' && process.env['TRAVIS_EVENT_TYPE'] !== 'api') { + console.log(`${chalk.green('NOBUILD')} Testing terminated, not a cron job or a custom build!`); + process.exit(0); +} +// Declare paths const SNIPPETS_PATH = './snippets'; const TEST_PATH = './test'; +// Array of snippet names const snippetFiles = fs.readdirSync(SNIPPETS_PATH, 'utf8').map(fileName => fileName.slice(0, -3)); -fs.removeSync(TEST_PATH); +// Current Snippet that depend on node_modules +const errSnippets = ['JSONToFile', 'readFileLines', 'UUIDGeneratorNode']; snippetFiles + .filter(fileName => !errSnippets.includes(fileName)) .map(fileName => { + // Check if fileName for snippet exist in test/ dir, if doesnt create fs.ensureDirSync(`${TEST_PATH}/${fileName}`); + + // return fileName for later use return fileName; }) .map(fileName => { + // Grab snippetData const fileData = fs.readFileSync(`${SNIPPETS_PATH}/${fileName}.md`, 'utf8'); + // Grab snippet Code blocks const fileCode = fileData.slice(fileData.indexOf('```js'), fileData.lastIndexOf('```') + 3); + // Split code based on code markers const blockMarkers = fileCode .split('\n') .map((line, lineIndex) => (line.slice(0, 3) === '```' ? lineIndex : '//CLEAR//')) .filter(x => !(x === '//CLEAR//')); + // Grab snippet function based on code markers const fileFunction = fileCode .split('\n') .map(line => line.trim()) .filter((_, i) => blockMarkers[0] < i && i < blockMarkers[1]); + // Grab snippet example based on code markers const fileExample = fileCode .split('\n') .map(line => line.trim()) .filter((_, i) => blockMarkers[2] < i && i < blockMarkers[3]); - const exportFile = `module.exports = ${fileFunction.join('\n').slice(17)}`; + // Export template for snippetName.js which takes into account snippet name.length when generating snippetName.js file + const exportFile = `module.exports = ${fileFunction.join('\n').slice(9 + fileName.length)}`; + + // Export template for snippetName.test.js which generates a example test & other information const exportTest = [ `const test = require('tape');`, `const ${fileName} = require('./${fileName}.js');`, - `test('Testing ${fileName}', (t) => {`, - `//For more information on all the methods supported by tape\n//Please go to https://github.com/substack/tape`, - `//t.deepEqual(${fileName}(args..), 'Expected');`, - `//t.equal(${fileName}(args..), 'Expected');`, - `//t.false(${fileName}(args..), 'Expected');`, - `//t.true(${fileName}(args..), 'Expected');`, - `//t.throws(${fileName}(args..), 'Expected');`, - `t.end();`, + `\ntest('Testing ${fileName}', (t) => {`, + `\t//For more information on all the methods supported by tape\n\t//Please go to https://github.com/substack/tape`, + `\tt.true(typeof ${fileName} === 'function', '${fileName} is a Function');`, + `\t//t.deepEqual(${fileName}(args..), 'Expected');`, + `\t//t.equal(${fileName}(args..), 'Expected');`, + `\t//t.false(${fileName}(args..), 'Expected');`, + `\t//t.throws(${fileName}(args..), 'Expected');`, + `\tt.end();`, `});` ].join('\n'); + // Write/Update exportFile which is snippetName.js in respective dir fs.writeFileSync(`${TEST_PATH}/${fileName}/${fileName}.js`, exportFile); - fs.writeFileSync(`${TEST_PATH}/${fileName}/${fileName}.test.js`, exportTest); + if ( !fs.existsSync(`${TEST_PATH}/${fileName}/${fileName}.test.js`) ) { + // if snippetName.test.js doesn't exist inrespective dir exportTest + fs.writeFileSync(`${TEST_PATH}/${fileName}/${fileName}.test.js`, exportTest); + } + + // return fileName for later use return fileName; }); + diff --git a/snippets/factors.md b/snippets/factors.md new file mode 100644 index 000000000..0e31b5dd5 --- /dev/null +++ b/snippets/factors.md @@ -0,0 +1,42 @@ +### factors + +Returns the array of factors of the given `num`. +If the second argument is set to `true` returns only the prime factors of `num`. +If `num` is `1` or `0` returns an empty array. +If `num` is less than `0` returns all the factors of `-int` together with their additive inverses. + +Use `Array.from()`, `Array.map()` and `Array.filter()` to find all the factors of `num`. +If given `num` is negative, use `Array.reduce()` to add the additive inverses to the array. +Return all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.filter()`. +Omit the second argument, `primes`, to return prime and non-prime factors by default. + +**Note**:- _Negative numbers are not considered prime._ + +```js +const factors = (num, primes = false) => { + const isPrime = num => { + const boundary = Math.floor(Math.sqrt(num)); + for (var i = 2; i <= boundary; i++) if (num % i === 0) return false; + return num >= 2; + }; + const isNeg = num < 0; + num = isNeg ? -num : num; + let array = Array.from({ length: num - 1 }) + .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false)) + .filter(val => val); + if (isNeg) + array = array.reduce((acc, val) => { + acc.push(val); + acc.push(-val); + return acc; + }, []); + return primes ? array.filter(isPrime) : array; +}; +``` + +```js +factors(12); // [2,3,4,6,12] +factors(12, true); // [2,3] +factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12] +factors(-12, true); // [2,3] +``` diff --git a/snippets/howManyTimes.md b/snippets/howManyTimes.md new file mode 100644 index 000000000..add649172 --- /dev/null +++ b/snippets/howManyTimes.md @@ -0,0 +1,32 @@ +### howManyTimes + +Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer. +Works for both negative and positive integers. + +If `divisor` is `-1` or `1` return `Infinity`. +If `divisor` is `-0` or `0` return `0`. +Otherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer. +Return the number of times the loop was executed, `i`. + +```js +const howManyTimes = (num, divisor) => { + if (divisor === 1 || divisor === -1) return Infinity; + if (divisor === 0) return 0; + let i = 0; + while (Number.isInteger(num / divisor)) { + i++; + num = num / divisor; + } + return i; +}; +``` + +```js +howManyTimes(100, 2); //2 +howManyTimes(100, -2); //2 +howManyTimes(100, 2.5); //2 +howManyTimes(100, 3); //0 +howManyTimes(100, 0); //0 +howManyTimes(100, 1); //Infinity +howManyTimes(100, -1); //Infinity +``` diff --git a/snippets/maxN.md b/snippets/maxN.md index efc9e5052..87ee686fd 100644 --- a/snippets/maxN.md +++ b/snippets/maxN.md @@ -1,10 +1,11 @@ ### maxN -Returns the `n` maximum elements from the provided array. If `n` is greater than or equal to the provided array's length than return the original array(sorted in descending order). +Returns the `n` maximum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in descending order). -Sort's the array's shallow copy in descending order and returns the first n elements +Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in descending order. +Use `Array.slice()` to get the specified number of elements. +Omit the second argument, `n`, to get a one-element array. -Skip the second argument to get a single element(in the form of a array) ```js const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); ``` diff --git a/snippets/minN.md b/snippets/minN.md index 2cee5b091..a97c5e1f7 100644 --- a/snippets/minN.md +++ b/snippets/minN.md @@ -1,10 +1,11 @@ ### minN -Returns the `n` minimum elements from the provided array. If `n` is greater than or equal to the provided array's length than return the original array(sorted in ascending order). +Returns the `n` minimum elements from the provided array. If `n` is greater than or equal to the provided array's length, then return the original array(sorted in ascending order). -Sort's the array's shallow copy in ascending order and returns the first n elements +Use `Array.sort()` combined with the spread operator (`...`) to create a shallow clone of the array and sort it in ascending order. +Use `Array.slice()` to get the specified number of elements. +Omit the second argument, `n`, to get a one-element array. -Skip the second argument to get a single element(in the form of a array) ```js const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); ``` diff --git a/snippets/pluralize.md b/snippets/pluralize.md new file mode 100644 index 000000000..decf1c2ef --- /dev/null +++ b/snippets/pluralize.md @@ -0,0 +1,23 @@ +# pluralize + +If `num` is greater than `1` returns the plural form of the given string, else return the singular form. + +Check if `num` is greater than `0`. Throw an appropriate `Error` if not, return the appropriate string otherwise. +Omit the third argument, `items`, to use a default plural form same as `item` suffixed with a single `'s'`. + +```js +const pluralize = (num, item, items = item + 's') => + num <= 0 + ? (() => { + throw new Error(`'num' should be >= 1. Value povided was ${num}.`); + })() + : num === 1 ? item : items; +``` + +```js +pluralize(1, 'apple', 'apples'); // 'apple' +pluralize(3, 'apple', 'apples'); // 'apples' +pluralize(2, 'apple'); // 'apples' +pluralize(0, 'apple', 'apples'); // Gives error +pluralize(-3, 'apple', 'apples'); // Gives error +``` diff --git a/static-parts/README-start.md b/static-parts/README-start.md index a3a94d299..34775afdc 100644 --- a/static-parts/README-start.md +++ b/static-parts/README-start.md @@ -5,7 +5,7 @@ [![License](https://img.shields.io/badge/license-CC0--1.0-blue.svg)](https://github.com/Chalarangelo/30-seconds-of-code/blob/master/LICENSE) [![Gitter chat](https://img.shields.io/badge/chat-on%20gitter-4FB999.svg)](https://gitter.im/30-seconds-of-code/Lobby) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](http://makeapullrequest.com) [![Travis Build](https://travis-ci.org/Chalarangelo/30-seconds-of-code.svg?branch=master)](https://travis-ci.org/Chalarangelo/30-seconds-of-code) [![Insight.io](https://img.shields.io/badge/insight.io-Ready-brightgreen.svg)](https://insight.io/github.com/Chalarangelo/30-seconds-of-code/tree/master/?source=0) [![js-semistandard-style](https://img.shields.io/badge/code%20style-semistandard-brightgreen.svg)](https://github.com/Flet/semistandard) [![ProductHunt](https://img.shields.io/badge/producthunt-vote-orange.svg)](https://www.producthunt.com/posts/30-seconds-of-code) -> Curated collection of useful Javascript snippets that you can understand in 30 seconds or less. +> Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less. - Use Ctrl + F or command + F to search for a snippet. @@ -13,6 +13,57 @@ - Snippets are written in ES6, use the [Babel transpiler](https://babeljs.io/) to ensure backwards-compatibility. - You can import these snippets into your text editor of choice (VSCode, Atom, Sublime) using the files found in [this repo](https://github.com/Rob-Rychs/30-seconds-of-code-texteditorsnippets). - You can import these snippets into Alfred 3, using [this file](https://github.com/lslvxy/30-seconds-of-code-alfredsnippets). -- You can find a package with all the snippets on [npm](https://www.npmjs.com/package/30-seconds-of-code). Bear in mind that most of these snippets are not production-ready. + +#### Package + +⚠️ **WARNING:** Snippets are not production ready. + +You can find a package with all the snippets on [npm](https://www.npmjs.com/package/30-seconds-of-code). + +``` +npm install 30-seconds-of-code +``` + +CDN links +- [ES2017 Full (UMD)](https://unpkg.com/30-seconds-of-code) +- [ES5 Minified (UMD)](https://unpkg.com/30-seconds-of-code/dist/_30s.es5.min.js) + +
    + +**Browser** + +> IMPORTANT: replace the `src` with the full version link and desired target spec (such as ES5 minified)): + +```html + + +``` + +**Node** + +```js +// CommonJS +const _30s = require('30-seconds-of-code'); +_30s.average(1, 2, 3); + +// ES Modules +import _30s from '30-seconds-of-code'; +_30s.average(1, 2, 3); +``` + +To import snippets directly: + +```js +// CommonJS +const { average } = require('30-seconds-of-code'); +average(1, 2, 3); + +// ES Modules +import { average } from '30-seconds-of-code'; +average(1, 2, 3); +``` +
    ## Table of Contents diff --git a/tag_database b/tag_database index 7b4e92890..5ef49198b 100644 --- a/tag_database +++ b/tag_database @@ -39,6 +39,7 @@ escapeRegExp:string everyNth:array extendHex:utility factorial:math +factors:math fibonacci:math fibonacciCountUntilNum:math fibonacciUntilNum:math @@ -49,7 +50,7 @@ flip:adapter fromCamelCase:string functionName:function gcd:math -geometricProgression:uncategorized +geometricProgression:math getDaysDiffBetweenDates:date getScrollPosition:browser getStyle:browser @@ -62,6 +63,7 @@ hasFlags:node head:array hexToRGB:utility hide:browser +howManyTimes:math httpsRedirect:browser initial:array initialize2DArray:array @@ -96,10 +98,10 @@ lcm:math lowercaseKeys:object mapObject:array mask:string -maxN:math +maxN:array median:math memoize:function -minN:math +minN:array negate:logic nthElement:array objectFromPairs:object @@ -111,6 +113,7 @@ palindrome:string percentile:math pick:array pipeFunctions:adapter +pluralize:string powerset:math prettyBytes:utility primes:math diff --git a/yarn.lock b/yarn.lock index c7dec9cb4..98cfbe791 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1093,6 +1093,10 @@ doctrine@^2.0.0: dependencies: esutils "^2.0.2" +duplexer@^0.1.1: + version "0.1.1" + resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.1.tgz#ace6ff808c1ce66b57d1ebf97977acb02334cfc1" + ecc-jsbn@~0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz#0fc73a9ed5f0d53c38193398523ef7e543777505" @@ -1379,7 +1383,7 @@ fast-levenshtein@~2.0.4: version "2.0.6" resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" -figures@^1.3.5: +figures@^1.3.5, figures@^1.4.0: version "1.7.0" resolved "https://registry.yarnpkg.com/figures/-/figures-1.7.0.tgz#cbe1e3affcf1cd44b80cadfed28dc793a9701d2e" dependencies: @@ -1758,7 +1762,7 @@ is-date-object@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.1.tgz#9aa20eb6aeebbff77fbd33e74ca01b33581d3a16" -is-finite@^1.0.0: +is-finite@^1.0.0, is-finite@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/is-finite/-/is-finite-1.0.2.tgz#cc6677695602be550ef11e8b4aa6305342b6d0aa" dependencies: @@ -1995,6 +1999,10 @@ lodash.some@^4.6.0: version "4.6.0" resolved "https://registry.yarnpkg.com/lodash.some/-/lodash.some-4.6.0.tgz#1bb9f314ef6b8baded13b549169b2a945eb68e4d" +lodash@^3.6.0: + version "3.10.1" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6" + lodash@^4.0.0, lodash@^4.17.4, lodash@^4.3.0, lodash@~4.17.4: version "4.17.4" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.4.tgz#78203a4d1c328ae1d86dca6460e369b57f4055ae" @@ -2272,6 +2280,10 @@ parse-json@^2.2.0: dependencies: error-ex "^1.2.0" +parse-ms@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/parse-ms/-/parse-ms-1.0.1.tgz#56346d4749d78f23430ca0c713850aef91aa361d" + path-exists@^2.0.0: version "2.1.0" resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-2.1.0.tgz#0feb6c64f0fc518d9a754dd5efb62c7022761f4b" @@ -2347,6 +2359,10 @@ pkg-up@^1.0.0: dependencies: find-up "^1.0.0" +plur@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/plur/-/plur-1.0.0.tgz#db85c6814f5e5e5a3b49efc28d604fec62975156" + pluralize@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-1.2.1.tgz#d1a21483fd22bb41e58a12fa3421823140897c45" @@ -2359,6 +2375,14 @@ prettier@^1.9.2: version "1.9.2" resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.9.2.tgz#96bc2132f7a32338e6078aeb29727178c6335827" +pretty-ms@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/pretty-ms/-/pretty-ms-2.1.0.tgz#4257c256df3fb0b451d6affaab021884126981dc" + dependencies: + is-finite "^1.0.1" + parse-ms "^1.0.0" + plur "^1.0.0" + private@^0.1.6, private@^0.1.7: version "0.1.8" resolved "https://registry.yarnpkg.com/private/-/private-0.1.8.tgz#2381edb3689f7a53d653190060fcf822d2f368ff" @@ -2387,6 +2411,10 @@ qs@~6.5.1: version "6.5.1" resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.1.tgz#349cdf6eef89ec45c12d7d5eb3fc0c870343a6d8" +re-emitter@^1.0.0: + version "1.1.3" + resolved "https://registry.yarnpkg.com/re-emitter/-/re-emitter-1.1.3.tgz#fa9e319ffdeeeb35b27296ef0f3d374dac2f52a7" + read-pkg-up@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz#9d63c13276c065918d57f002a57f40a1b643fb02" @@ -2402,7 +2430,7 @@ read-pkg@^1.0.0: normalize-package-data "^2.3.2" path-type "^1.0.0" -readable-stream@^2.0.1, readable-stream@^2.0.6, readable-stream@^2.2.2: +readable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.6, readable-stream@^2.1.5, readable-stream@^2.2.2: version "2.3.3" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.3.tgz#368f2512d79f9d46fdfc71349ae7878bbc1eb95c" dependencies: @@ -2473,6 +2501,10 @@ relateurl@0.2.x: version "0.2.7" resolved "https://registry.yarnpkg.com/relateurl/-/relateurl-0.2.7.tgz#54dbf377e51440aca90a4cd274600d3ff2d888a9" +repeat-string@^1.5.2: + version "1.6.1" + resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" + repeating@^2.0.0: version "2.0.1" resolved "https://registry.yarnpkg.com/repeating/-/repeating-2.0.1.tgz#5214c53a926d3552707527fbab415dbc08d06dda" @@ -2733,6 +2765,12 @@ spdx-license-ids@^1.0.2: version "1.2.2" resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz#c9df7a3424594ade6bd11900d596696dc06bac57" +split@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/split/-/split-1.0.1.tgz#605bd9be303aa59fb35f9229fbea0ddec9ea07d9" + dependencies: + through "2" + sprintf-js@~1.0.2: version "1.0.3" resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" @@ -2852,6 +2890,28 @@ table@^3.7.8: slice-ansi "0.0.4" string-width "^2.0.0" +tap-out@^1.4.1: + version "1.4.2" + resolved "https://registry.yarnpkg.com/tap-out/-/tap-out-1.4.2.tgz#c907ec1bf9405111d088263e92f5608b88cbb37a" + dependencies: + re-emitter "^1.0.0" + readable-stream "^2.0.0" + split "^1.0.0" + trim "0.0.1" + +tap-spec@^4.1.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/tap-spec/-/tap-spec-4.1.1.tgz#e2e9f26f5208232b1f562288c97624d58a88f05a" + dependencies: + chalk "^1.0.0" + duplexer "^0.1.1" + figures "^1.4.0" + lodash "^3.6.0" + pretty-ms "^2.1.0" + repeat-string "^1.5.2" + tap-out "^1.4.1" + through2 "^2.0.0" + tape@^4.8.0: version "4.8.0" resolved "https://registry.yarnpkg.com/tape/-/tape-4.8.0.tgz#f6a9fec41cc50a1de50fa33603ab580991f6068e" @@ -2882,7 +2942,14 @@ text-table@~0.2.0: version "0.2.0" resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4" -through@^2.3.6, through@~2.3.4, through@~2.3.8: +through2@^2.0.0: + version "2.0.3" + resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.3.tgz#0004569b37c7c74ba39c43f3ced78d1ad94140be" + dependencies: + readable-stream "^2.1.5" + xtend "~4.0.1" + +through@2, through@^2.3.6, through@~2.3.4, through@~2.3.8: version "2.3.8" resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" @@ -2904,6 +2971,10 @@ trim-right@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/trim-right/-/trim-right-1.0.1.tgz#cb2e1203067e0c8de1f614094b9fe45704ea6003" +trim@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/trim/-/trim-0.0.1.tgz#5858547f6b290757ee95cccc666fb50084c460dd" + "true-case-path@^1.0.2": version "1.0.2" resolved "https://registry.yarnpkg.com/true-case-path/-/true-case-path-1.0.2.tgz#7ec91130924766c7f573be3020c34f8fdfd00d62" @@ -3027,7 +3098,7 @@ xml-char-classes@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/xml-char-classes/-/xml-char-classes-1.0.0.tgz#64657848a20ffc5df583a42ad8a277b4512bbc4d" -xtend@^4.0.0, xtend@^4.0.1: +xtend@^4.0.0, xtend@^4.0.1, xtend@~4.0.1: version "4.0.1" resolved "https://registry.yarnpkg.com/xtend/-/xtend-4.0.1.tgz#a5c6d532be656e23db820efb943a1f04998d63af"