diff --git a/dist/_30s.es5.js b/dist/_30s.es5.js index de2f6ad74..cbcbf9aa0 100644 --- a/dist/_30s.es5.js +++ b/dist/_30s.es5.js @@ -1,33 +1,8 @@ (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global._30s = {}))); -}(this, (function (exports) { 'use strict'; - - var CSVToArray = function CSVToArray(data) { - var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ','; - var omitFirstRow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; - return data.slice(omitFirstRow ? data.indexOf('\n') + 1 : 0).split('\n').map(function (v) { - return v.split(delimiter); - }); - }; - - var CSVToJSON = function CSVToJSON(data) { - var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ','; - var titles = data.slice(0, data.indexOf('\n')).split(delimiter); - return data.slice(data.indexOf('\n') + 1).split('\n').map(function (v) { - var values = v.split(delimiter); - return titles.reduce(function (obj, title, index) { - return obj[title] = values[index], obj; - }, {}); - }); - }; - - var fs = typeof require !== "undefined" && require('fs'); - - var JSONToFile = function JSONToFile(obj, filename) { - return fs.writeFile("".concat(filename, ".json"), JSON.stringify(obj, null, 2)); - }; + typeof exports === 'object' && typeof module !== 'undefined' ? factory() : + typeof define === 'function' && define.amd ? define(factory) : + (factory()); +}(this, (function () { 'use strict'; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { @@ -139,40 +114,9 @@ throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - var JSONtoCSV = function JSONtoCSV(arr, columns) { - var delimiter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ','; - return [columns.join(delimiter)].concat(_toConsumableArray(arr.map(function (obj) { - return columns.reduce(function (acc, key) { - return "".concat(acc).concat(!acc.length ? '' : delimiter, "\"").concat(!obj[key] ? '' : obj[key], "\""); - }, ''); - }))).join('\n'); - }; + var crypto = typeof require !== "undefined" && require('crypto'); - var RGBToHex = function RGBToHex(r, g, b) { - return ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); - }; - - var URLJoin = function URLJoin() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return args.join('/').replace(/[\/]+/g, '/').replace(/^(.+):\//, '$1://').replace(/^file:/, 'file:/').replace(/\/(\?|&|#[^!])/g, '$1').replace(/\?/g, '&').replace('&', '?'); - }; - - 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 fs = typeof require !== "undefined" && require('fs'); var all = function all(arr) { var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Boolean; @@ -228,8 +172,8 @@ var attempt = function attempt(fn) { try { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; + for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { + args[_key2 - 1] = arguments[_key2]; } return fn.apply(void 0, args); @@ -239,8 +183,8 @@ }; var average = function average() { - for (var _len = arguments.length, nums = new Array(_len), _key = 0; _key < _len; _key++) { - nums[_key] = arguments[_key]; + for (var _len3 = arguments.length, nums = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + nums[_key3] = arguments[_key3]; } return nums.reduce(function (acc, val) { @@ -269,13 +213,13 @@ }; var bind = function bind(fn, context) { - for (var _len = arguments.length, boundArgs = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - boundArgs[_key - 2] = arguments[_key]; + for (var _len4 = arguments.length, boundArgs = new Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) { + boundArgs[_key4 - 2] = arguments[_key4]; } return function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; + for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { + args[_key5] = arguments[_key5]; } return fn.apply(context, boundArgs.concat(args)); @@ -283,8 +227,8 @@ }; var bindAll = function bindAll(obj) { - for (var _len = arguments.length, fns = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - fns[_key - 1] = arguments[_key]; + for (var _len6 = arguments.length, fns = new Array(_len6 > 1 ? _len6 - 1 : 0), _key6 = 1; _key6 < _len6; _key6++) { + fns[_key6 - 1] = arguments[_key6]; } return fns.forEach(function (fn) { @@ -295,13 +239,13 @@ }; var bindKey = function bindKey(context, fn) { - for (var _len = arguments.length, boundArgs = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - boundArgs[_key - 2] = arguments[_key]; + for (var _len7 = arguments.length, boundArgs = new Array(_len7 > 2 ? _len7 - 2 : 0), _key7 = 2; _key7 < _len7; _key7++) { + boundArgs[_key7 - 2] = arguments[_key7]; } return function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; + for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { + args[_key8] = arguments[_key8]; } return context[fn].apply(context, boundArgs.concat(args)); @@ -336,8 +280,8 @@ }; var call = function call(key) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; + for (var _len9 = arguments.length, args = new Array(_len9 > 1 ? _len9 - 1 : 0), _key9 = 1; _key9 < _len9; _key9++) { + args[_key9 - 1] = arguments[_key9]; } return function (context) { @@ -391,8 +335,8 @@ }; var coalesce = function coalesce() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { + args[_key10] = arguments[_key10]; } return args.find(function (_) { @@ -402,8 +346,8 @@ var coalesceFactory = function coalesceFactory(valid) { return function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) { + args[_key11] = arguments[_key11]; } return args.find(valid); @@ -412,8 +356,8 @@ var collectInto = function collectInto(fn) { return function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len12 = arguments.length, args = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) { + args[_key12] = arguments[_key12]; } return fn(args); @@ -421,8 +365,8 @@ }; var colorize = function colorize() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len13 = arguments.length, args = new Array(_len13), _key13 = 0; _key13 < _len13; _key13++) { + args[_key13] = arguments[_key13]; } return { @@ -450,8 +394,8 @@ }; var compose = function compose() { - for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) { - fns[_key] = arguments[_key]; + for (var _len14 = arguments.length, fns = new Array(_len14), _key14 = 0; _key14 < _len14; _key14++) { + fns[_key14] = arguments[_key14]; } return fns.reduce(function (f, g) { @@ -462,8 +406,8 @@ }; var composeRight = function composeRight() { - for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) { - fns[_key] = arguments[_key]; + for (var _len15 = arguments.length, fns = new Array(_len15), _key15 = 0; _key15 < _len15; _key15++) { + fns[_key15] = arguments[_key15]; } return fns.reduce(function (f, g) { @@ -475,8 +419,8 @@ var converge = function converge(converger, fns) { return function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len16 = arguments.length, args = new Array(_len16), _key16 = 0; _key16 < _len16; _key16++) { + args[_key16] = arguments[_key16]; } return converger.apply(void 0, _toConsumableArray(fns.map(function (fn) { @@ -506,18 +450,12 @@ var countBy = function countBy(arr, fn) { return arr.map(typeof fn === 'function' ? fn : function (val) { return val[fn]; - }).reduce(function (acc, val, i) { + }).reduce(function (acc, val) { acc[val] = (acc[val] || 0) + 1; return acc; }, {}); }; - var countOccurrences = function countOccurrences(arr, val) { - return arr.reduce(function (a, v) { - return v === val ? a + 1 : a; - }, 0); - }; - var counter = function counter(selector, start, end) { var step = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; var duration = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 2000; @@ -534,6 +472,12 @@ return timer; }; + var countOccurrences = function countOccurrences(arr, val) { + return arr.reduce(function (a, v) { + return v === val ? a + 1 : a; + }, 0); + }; + var createElement = function createElement(str) { var el = document.createElement('div'); el.innerHTML = str; @@ -561,6 +505,25 @@ }; }; + var CSVToArray = function CSVToArray(data) { + var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ','; + var omitFirstRow = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + return data.slice(omitFirstRow ? data.indexOf('\n') + 1 : 0).split('\n').map(function (v) { + return v.split(delimiter); + }); + }; + + var CSVToJSON = function CSVToJSON(data) { + var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ','; + var titles = data.slice(0, data.indexOf('\n')).split(delimiter); + return data.slice(data.indexOf('\n') + 1).split('\n').map(function (v) { + var values = v.split(delimiter); + return titles.reduce(function (obj, title, index) { + return obj[title] = values[index], obj; + }, {}); + }); + }; + var currentURL = function currentURL() { return window.location.href; }; @@ -568,8 +531,8 @@ var curry = function curry(fn) { var arity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : fn.length; - for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - args[_key - 2] = arguments[_key]; + for (var _len17 = arguments.length, args = new Array(_len17 > 2 ? _len17 - 2 : 0), _key17 = 2; _key17 < _len17; _key17++) { + args[_key17 - 2] = arguments[_key17]; } return arity <= args.length ? fn.apply(void 0, args) : curry.bind.apply(curry, [null, fn, arity].concat(args)); @@ -585,8 +548,8 @@ return function () { var _this = this; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) { + args[_key18] = arguments[_key18]; } clearTimeout(timeoutId); @@ -596,10 +559,10 @@ }; }; - var decapitalize = function decapitalize(_ref) { - var _ref2 = _toArray(_ref), - first = _ref2[0], - rest = _ref2.slice(1); + var decapitalize = function decapitalize(_ref3) { + var _ref4 = _toArray(_ref3), + first = _ref4[0], + rest = _ref4.slice(1); var upperRest = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join('')); @@ -614,30 +577,30 @@ }; var deepFlatten = function deepFlatten(arr) { - var _ref; + var _ref5; - return (_ref = []).concat.apply(_ref, _toConsumableArray(arr.map(function (v) { + return (_ref5 = []).concat.apply(_ref5, _toConsumableArray(arr.map(function (v) { return Array.isArray(v) ? deepFlatten(v) : v; }))); }; var deepFreeze = function deepFreeze(obj) { return Object.keys(obj).forEach(function (prop) { - return !obj[prop] instanceof Object || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop]); + return !(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop]); }) || Object.freeze(obj); }; var defaults = function defaults(obj) { - for (var _len = arguments.length, defs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - defs[_key - 1] = arguments[_key]; + for (var _len19 = arguments.length, defs = new Array(_len19 > 1 ? _len19 - 1 : 0), _key19 = 1; _key19 < _len19; _key19++) { + defs[_key19 - 1] = arguments[_key19]; } return Object.assign.apply(Object, [{}, obj].concat(_toConsumableArray(defs.reverse()), [obj])); }; var defer = function defer(fn) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; + for (var _len20 = arguments.length, args = new Array(_len20 > 1 ? _len20 - 1 : 0), _key20 = 1; _key20 < _len20; _key20++) { + args[_key20 - 1] = arguments[_key20]; } return setTimeout.apply(void 0, [fn, 1].concat(args)); @@ -648,8 +611,8 @@ }; var delay = function delay(fn, wait) { - for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - args[_key - 2] = arguments[_key]; + for (var _len21 = arguments.length, args = new Array(_len21 > 2 ? _len21 - 2 : 0), _key21 = 2; _key21 < _len21; _key21++) { + args[_key21 - 2] = arguments[_key21]; } return setTimeout.apply(void 0, [fn, wait].concat(args)); @@ -667,9 +630,7 @@ }; var differenceBy = function differenceBy(a, b, fn) { - var s = new Set(b.map(function (v) { - return fn(v); - })); + var s = new Set(b.map(fn)); return a.filter(function (x) { return !s.has(fn(x)); }); @@ -745,9 +706,9 @@ return partiallyVisible ? (top > 0 && top < innerHeight || bottom > 0 && bottom < innerHeight) && (left > 0 && left < innerWidth || right > 0 && right < innerWidth) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }; - var elo = function elo(_ref) { - var _ref2 = _toArray(_ref), - ratings = _ref2.slice(0); + var elo = function elo(_ref6) { + var _ref7 = _toArray(_ref6), + ratings = _ref7.slice(0); var kFactor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 32; var selfRating = arguments.length > 2 ? arguments[2] : undefined; @@ -764,9 +725,7 @@ return (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a)); }; - if (ratings.length === 2) { - return [newRating(a, 1), newRating(b, 0)]; - } + if (ratings.length === 2) return [newRating(a, 1), newRating(b, 0)]; for (var i = 0, len = ratings.length; i < len; i++) { var j = i; @@ -868,10 +827,10 @@ var findLastIndex = function findLastIndex(arr, fn) { return arr.map(function (val, i) { return [i, val]; - }).filter(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - i = _ref2[0], - val = _ref2[1]; + }).filter(function (_ref8) { + var _ref9 = _slicedToArray(_ref8, 2), + i = _ref9[0], + val = _ref9[1]; return fn(val, i, arr); }).pop()[0]; @@ -901,8 +860,8 @@ var flip = function flip(fn) { return function (first) { - for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - rest[_key - 1] = arguments[_key]; + for (var _len22 = arguments.length, rest = new Array(_len22 > 1 ? _len22 - 1 : 0), _key22 = 1; _key22 < _len22; _key22++) { + rest[_key22 - 1] = arguments[_key22]; } return fn.apply(void 0, rest.concat([first])); @@ -913,18 +872,6 @@ return arr.slice(0).reverse().forEach(callback); }; - var forOwn = function forOwn(obj, fn) { - return Object.keys(obj).forEach(function (key) { - return fn(obj[key], key, obj); - }); - }; - - var forOwnRight = function forOwnRight(obj, fn) { - return Object.keys(obj).reverse().forEach(function (key) { - return fn(obj[key], key, obj); - }); - }; - var formatDuration = function formatDuration(ms) { if (ms < 0) ms = -ms; var time = { @@ -936,15 +883,27 @@ }; return Object.entries(time).filter(function (val) { return val[1] !== 0; - }).map(function (_ref) { - var _ref2 = _slicedToArray(_ref, 2), - key = _ref2[0], - val = _ref2[1]; + }).map(function (_ref10) { + var _ref11 = _slicedToArray(_ref10, 2), + key = _ref11[0], + val = _ref11[1]; return "".concat(val, " ").concat(key).concat(val !== 1 ? 's' : ''); }).join(', '); }; + var forOwn = function forOwn(obj, fn) { + return Object.keys(obj).forEach(function (key) { + return fn(obj[key], key, obj); + }); + }; + + var forOwnRight = function forOwnRight(obj, fn) { + return Object.keys(obj).reverse().forEach(function (key) { + return fn(obj[key], key, obj); + }); + }; + var fromCamelCase = function fromCamelCase(str) { var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '_'; return str.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2').replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2').toLowerCase(); @@ -966,8 +925,8 @@ return !y ? x : gcd(y, x % y); }; - for (var _len = arguments.length, arr = new Array(_len), _key = 0; _key < _len; _key++) { - arr[_key] = arguments[_key]; + for (var _len23 = arguments.length, arr = new Array(_len23), _key23 = 0; _key23 < _len23; _key23++) { + arr[_key23] = arguments[_key23]; } return arr.concat().reduce(function (a, b) { @@ -986,8 +945,8 @@ }; var get = function get(from) { - for (var _len = arguments.length, selectors = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - selectors[_key - 1] = arguments[_key]; + for (var _len24 = arguments.length, selectors = new Array(_len24 > 1 ? _len24 - 1 : 0), _key24 = 1; _key24 < _len24; _key24++) { + selectors[_key24 - 1] = arguments[_key24]; } return selectors.concat().map(function (s) { @@ -1061,8 +1020,8 @@ }; var hasFlags = function hasFlags() { - for (var _len = arguments.length, flags = new Array(_len), _key = 0; _key < _len; _key++) { - flags[_key] = arguments[_key]; + for (var _len25 = arguments.length, flags = new Array(_len25), _key25 = 0; _key25 < _len25; _key25++) { + flags[_key25] = arguments[_key25]; } return flags.every(function (flag) { @@ -1083,12 +1042,10 @@ }); }; - var crypto$2 = typeof require !== "undefined" && require('crypto'); - var hashNode = function hashNode(val) { return new Promise(function (resolve) { return setTimeout(function () { - return resolve(crypto$2.createHash('sha256').update(val).digest('hex')); + return resolve(crypto.createHash('sha256').update(val).digest('hex')); }, 0); }); }; @@ -1161,18 +1118,6 @@ return 1000 * iterations / (performance.now() - before); }; - var inRange = function inRange(n, start) { - var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - - if (end && start > end) { - var _ref = [start, end]; - end = _ref[0]; - start = _ref[1]; - } - - return end == null ? n >= 0 && n < start : n >= start && n < end; - }; - var indentString = function indentString(str, count) { var indent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ' '; return str.replace(/^/gm, indent.repeat(count)); @@ -1225,8 +1170,8 @@ }; var initializeNDArray = function initializeNDArray(val) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; + for (var _len26 = arguments.length, args = new Array(_len26 > 1 ? _len26 - 1 : 0), _key26 = 1; _key26 < _len26; _key26++) { + args[_key26 - 1] = arguments[_key26]; } return args.length === 0 ? val : Array.from({ @@ -1236,6 +1181,18 @@ }); }; + var inRange = function inRange(n, start) { + var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + + if (end && start > end) { + var _ref12 = [start, end]; + end = _ref12[0]; + start = _ref12[1]; + } + + return end == null ? n >= 0 && n < start : n >= start && n < end; + }; + var insertAfter = function insertAfter(el, htmlString) { return el.insertAdjacentHTML('afterend', htmlString); }; @@ -1374,7 +1331,7 @@ }; var isPrimitive = function isPrimitive(val) { - return !['object', 'function'].includes(_typeof(val)) || val === null; + return Object(val) !== val; }; var isPromiseLike = function isPromiseLike(obj) { @@ -1396,10 +1353,10 @@ var _iteratorError = undefined; try { - for (var _iterator = arr.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var _step$value = _slicedToArray(_step.value, 2), - i = _step$value[0], - val = _step$value[1]; + for (var _iterator = arr.entries()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion = (_step2 = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _step2$value = _slicedToArray(_step2.value, 2), + i = _step2$value[0], + val = _step2$value[1]; direction = !direction ? -(arr[i - 1] - arr[i]) : direction; if (i === arr.length - 1) return !direction ? 0 : direction;else if ((val - arr[i + 1]) * direction > 0) return 0; @@ -1465,6 +1422,19 @@ }, ''); }; + var JSONtoCSV = function JSONtoCSV(arr, columns) { + var delimiter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ','; + return [columns.join(delimiter)].concat(_toConsumableArray(arr.map(function (obj) { + return columns.reduce(function (acc, key) { + return "".concat(acc).concat(!acc.length ? '' : delimiter, "\"").concat(!obj[key] ? '' : obj[key], "\""); + }, ''); + }))).join('\n'); + }; + + var JSONToFile = function JSONToFile(obj, filename) { + return fs.writeFile("".concat(filename, ".json"), JSON.stringify(obj, null, 2)); + }; + var last = function last(arr) { return arr[arr.length - 1]; }; @@ -1478,8 +1448,8 @@ return x * y / gcd(x, y); }; - for (var _len = arguments.length, arr = new Array(_len), _key = 0; _key < _len; _key++) { - arr[_key] = arguments[_key]; + for (var _len27 = arguments.length, arr = new Array(_len27), _key27 = 0; _key27 < _len27; _key27++) { + arr[_key27] = arguments[_key27]; } return arr.concat().reduce(function (a, b) { @@ -1488,8 +1458,8 @@ }; var longestItem = function longestItem(val) { - for (var _len = arguments.length, vals = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - vals[_key - 1] = arguments[_key]; + for (var _len28 = arguments.length, vals = new Array(_len28 > 1 ? _len28 - 1 : 0), _key28 = 1; _key28 < _len28; _key28++) { + vals[_key28 - 1] = arguments[_key28]; } return [val].concat(vals).reduce(function (a, x) { @@ -1571,8 +1541,8 @@ var maxDate = function maxDate() { var _Math$max; - for (var _len = arguments.length, dates = new Array(_len), _key = 0; _key < _len; _key++) { - dates[_key] = arguments[_key]; + for (var _len29 = arguments.length, dates = new Array(_len29), _key29 = 0; _key29 < _len29; _key29++) { + dates[_key29] = arguments[_key29]; } return new Date((_Math$max = Math.max).apply.apply(_Math$max, [null].concat(dates))); @@ -1606,8 +1576,8 @@ }; var merge = function merge() { - for (var _len = arguments.length, objs = new Array(_len), _key = 0; _key < _len; _key++) { - objs[_key] = arguments[_key]; + for (var _len30 = arguments.length, objs = new Array(_len30), _key30 = 0; _key30 < _len30; _key30++) { + objs[_key30] = arguments[_key30]; } return objs.concat().reduce(function (acc, obj) { @@ -1627,8 +1597,8 @@ var minDate = function minDate() { var _Math$min; - for (var _len = arguments.length, dates = new Array(_len), _key = 0; _key < _len; _key++) { - dates[_key] = arguments[_key]; + for (var _len31 = arguments.length, dates = new Array(_len31), _key31 = 0; _key31 < _len31; _key31++) { + dates[_key31] = arguments[_key31]; } return new Date((_Math$min = Math.min).apply.apply(_Math$min, [null].concat(dates))); @@ -1684,8 +1654,8 @@ var nthArg = function nthArg(n) { return function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len32 = arguments.length, args = new Array(_len32), _key32 = 0; _key32 < _len32; _key32++) { + args[_key32] = arguments[_key32]; } return args.slice(n)[0]; @@ -1698,10 +1668,10 @@ }; var objectFromPairs = function objectFromPairs(arr) { - return arr.reduce(function (a, _ref) { - var _ref2 = _slicedToArray(_ref, 2), - key = _ref2[0], - val = _ref2[1]; + return arr.reduce(function (a, _ref13) { + var _ref14 = _slicedToArray(_ref13, 2), + key = _ref14[0], + val = _ref14[1]; return a[key] = val, a; }, {}); @@ -1766,6 +1736,20 @@ if (opts.target) return delegatorFn; }; + var once = function once(fn) { + var called = false; + return function () { + if (called) return; + called = true; + + for (var _len33 = arguments.length, args = new Array(_len33), _key33 = 0; _key33 < _len33; _key33++) { + args[_key33] = arguments[_key33]; + } + + return fn.apply(this, args); + }; + }; + var onUserInputChange = function onUserInputChange(callback) { var type = 'mouse', lastTime = 0; @@ -1782,28 +1766,14 @@ }); }; - var once = function once(fn) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return fn.apply(this, args); - }; - }; - var orderBy = function orderBy(arr, props, orders) { return _toConsumableArray(arr).sort(function (a, b) { return props.reduce(function (acc, prop, i) { if (acc === 0) { - var _ref = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]], - _ref2 = _slicedToArray(_ref, 2), - p1 = _ref2[0], - p2 = _ref2[1]; + var _ref15 = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]], + _ref16 = _slicedToArray(_ref15, 2), + p1 = _ref16[0], + p2 = _ref16[1]; acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0; } @@ -1814,13 +1784,13 @@ }; var over = function over() { - for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) { - fns[_key] = arguments[_key]; + for (var _len34 = arguments.length, fns = new Array(_len34), _key34 = 0; _key34 < _len34; _key34++) { + fns[_key34] = arguments[_key34]; } return function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; + for (var _len35 = arguments.length, args = new Array(_len35), _key35 = 0; _key35 < _len35; _key35++) { + args[_key35] = arguments[_key35]; } return fns.map(function (fn) { @@ -1831,8 +1801,8 @@ var overArgs = function overArgs(fn, transforms) { return function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len36 = arguments.length, args = new Array(_len36), _key36 = 0; _key36 < _len36; _key36++) { + args[_key36] = arguments[_key36]; } return fn.apply(void 0, _toConsumableArray(args.map(function (val, i) { @@ -1861,13 +1831,13 @@ }; var partial = function partial(fn) { - for (var _len = arguments.length, partials = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - partials[_key - 1] = arguments[_key]; + for (var _len37 = arguments.length, partials = new Array(_len37 > 1 ? _len37 - 1 : 0), _key37 = 1; _key37 < _len37; _key37++) { + partials[_key37 - 1] = arguments[_key37]; } return function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; + for (var _len38 = arguments.length, args = new Array(_len38), _key38 = 0; _key38 < _len38; _key38++) { + args[_key38] = arguments[_key38]; } return fn.apply(void 0, partials.concat(args)); @@ -1875,13 +1845,13 @@ }; var partialRight = function partialRight(fn) { - for (var _len = arguments.length, partials = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - partials[_key - 1] = arguments[_key]; + for (var _len39 = arguments.length, partials = new Array(_len39 > 1 ? _len39 - 1 : 0), _key39 = 1; _key39 < _len39; _key39++) { + partials[_key39 - 1] = arguments[_key39]; } return function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; + for (var _len40 = arguments.length, args = new Array(_len40), _key40 = 0; _key40 < _len40; _key40++) { + args[_key40] = arguments[_key40]; } return fn.apply(void 0, args.concat(partials)); @@ -1925,8 +1895,8 @@ }; var pipeAsyncFunctions = function pipeAsyncFunctions() { - for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) { - fns[_key] = arguments[_key]; + for (var _len41 = arguments.length, fns = new Array(_len41), _key41 = 0; _key41 < _len41; _key41++) { + fns[_key41] = arguments[_key41]; } return function (arg) { @@ -1937,8 +1907,8 @@ }; var pipeFunctions = function pipeFunctions() { - for (var _len = arguments.length, fns = new Array(_len), _key = 0; _key < _len; _key++) { - fns[_key] = arguments[_key]; + for (var _len42 = arguments.length, fns = new Array(_len42), _key42 = 0; _key42 < _len42; _key42++) { + fns[_key42] = arguments[_key42]; } return fns.reduce(function (f, g) { @@ -2011,8 +1981,8 @@ var promisify = function promisify(func) { return function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len43 = arguments.length, args = new Array(_len43), _key43 = 0; _key43 < _len43; _key43++) { + args[_key43] = arguments[_key43]; } return new Promise(function (resolve, reject) { @@ -2024,8 +1994,8 @@ }; var pull = function pull(arr) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; + for (var _len44 = arguments.length, args = new Array(_len44 > 1 ? _len44 - 1 : 0), _key44 = 1; _key44 < _len44; _key44++) { + args[_key44 - 1] = arguments[_key44]; } var argState = Array.isArray(args[0]) ? args[0] : args; @@ -2068,8 +2038,8 @@ }; var pullBy = function pullBy(arr) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; + for (var _len45 = arguments.length, args = new Array(_len45 > 1 ? _len45 - 1 : 0), _key45 = 1; _key45 < _len45; _key45++) { + args[_key45 - 1] = arguments[_key45]; } var length = args.length; @@ -2113,16 +2083,14 @@ return Math.random() * (max - min) + min; }; - var fs$1 = typeof require !== "undefined" && require('fs'); - var readFileLines = function readFileLines(filename) { - return fs$1.readFileSync(filename).toString('UTF8').split('\n'); + return fs.readFileSync(filename).toString('UTF8').split('\n'); }; var rearg = function rearg(fn, indexes) { return function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len46 = arguments.length, args = new Array(_len46), _key46 = 0; _key46 < _len46; _key46++) { + args[_key46] = arguments[_key46]; } return fn.apply(void 0, _toConsumableArray(indexes.map(function (i) { @@ -2165,6 +2133,15 @@ return asLink ? window.location.href = url : window.location.replace(url); }; + var reducedFilter = function reducedFilter(data, keys, fn) { + return data.filter(fn).map(function (el) { + return keys.reduce(function (acc, key) { + acc[key] = el[key]; + return acc; + }, {}); + }); + }; + var reduceSuccessive = function reduceSuccessive(arr, fn, acc) { return arr.reduce(function (res, val, i, arr) { return res.push(fn(res.slice(-1)[0], val, i, arr)), res; @@ -2180,15 +2157,6 @@ }); }; - var reducedFilter = function reducedFilter(data, keys, fn) { - return data.filter(fn).map(function (el) { - return keys.reduce(function (acc, key) { - acc[key] = el[key]; - return acc; - }, {}); - }); - }; - var reject = function reject(pred, array) { return array.filter(function () { return !pred.apply(void 0, arguments); @@ -2216,6 +2184,10 @@ return _toConsumableArray(str).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("".concat(Math.round("".concat(n, "e").concat(decimals)), "e-").concat(decimals)); @@ -2226,8 +2198,8 @@ type: 'application/javascript; charset=utf-8' })); return new Promise(function (res, rej) { - worker.onmessage = function (_ref) { - var data = _ref.data; + worker.onmessage = function (_ref17) { + var data = _ref17.data; res(data), worker.terminate(); }; @@ -2247,18 +2219,18 @@ return arr[Math.floor(Math.random() * arr.length)]; }; - var sampleSize = function sampleSize(_ref) { - var _ref2 = _toArray(_ref), - arr = _ref2.slice(0); + var sampleSize = function sampleSize(_ref18) { + var _ref19 = _toArray(_ref18), + arr = _ref19.slice(0); var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var m = arr.length; while (m) { var i = Math.floor(Math.random() * m--); - var _ref3 = [arr[i], arr[m]]; - arr[m] = _ref3[0]; - arr[i] = _ref3[1]; + var _ref20 = [arr[i], arr[m]]; + arr[m] = _ref20[0]; + arr[i] = _ref20[1]; } return arr.slice(0, n); @@ -2296,16 +2268,16 @@ var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var delCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - for (var _len = arguments.length, elements = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) { - elements[_key - 3] = arguments[_key]; + for (var _len47 = arguments.length, elements = new Array(_len47 > 3 ? _len47 - 3 : 0), _key47 = 3; _key47 < _len47; _key47++) { + elements[_key47 - 3] = arguments[_key47]; } return arr.slice(0, index).concat(elements).concat(arr.slice(index + delCount)); }; var show = function show() { - for (var _len = arguments.length, el = new Array(_len), _key = 0; _key < _len; _key++) { - el[_key] = arguments[_key]; + for (var _len48 = arguments.length, el = new Array(_len48), _key48 = 0; _key48 < _len48; _key48++) { + el[_key48] = arguments[_key48]; } return el.concat().forEach(function (e) { @@ -2313,17 +2285,17 @@ }); }; - var shuffle = function shuffle(_ref) { - var _ref2 = _toArray(_ref), - arr = _ref2.slice(0); + var shuffle = function shuffle(_ref21) { + var _ref22 = _toArray(_ref21), + arr = _ref22.slice(0); var m = arr.length; while (m) { var i = Math.floor(Math.random() * m--); - var _ref3 = [arr[i], arr[m]]; - arr[m] = _ref3[0]; - arr[i] = _ref3[1]; + var _ref23 = [arr[i], arr[m]]; + arr[m] = _ref23[0]; + arr[i] = _ref23[1]; } return arr; @@ -2409,8 +2381,8 @@ }; }).sort(function (a, b) { return compare(a.item, b.item) || a.index - b.index; - }).map(function (_ref) { - var item = _ref.item; + }).map(function (_ref24) { + var item = _ref24.item; return item; }); }; @@ -2441,8 +2413,8 @@ }; var sum = function sum() { - for (var _len = arguments.length, arr = new Array(_len), _key = 0; _key < _len; _key++) { - arr[_key] = arguments[_key]; + for (var _len49 = arguments.length, arr = new Array(_len49), _key49 = 0; _key49 < _len49; _key49++) { + arr[_key49] = arguments[_key49]; } return arr.concat().reduce(function (acc, val) { @@ -2525,29 +2497,29 @@ }; var takeWhile = function takeWhile(arr, func) { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; try { - for (var _iterator = arr.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var _step$value = _slicedToArray(_step.value, 2), - i = _step$value[0], - val = _step$value[1]; + for (var _iterator2 = arr.entries()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion2 = (_step3 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var _step3$value = _slicedToArray(_step3.value, 2), + i = _step3$value[0], + val = _step3$value[1]; if (func(val)) return arr.slice(0, i); } } catch (err) { - _didIteratorError = true; - _iteratorError = err; + _didIteratorError2 = true; + _iteratorError2 = err; } finally { try { - if (!_iteratorNormalCompletion && _iterator.return != null) { - _iterator.return(); + if (!_iteratorNormalCompletion2 && _iterator2.return != null) { + _iterator2.return(); } } finally { - if (_didIteratorError) { - throw _iteratorError; + if (_didIteratorError2) { + throw _iteratorError2; } } } @@ -2572,18 +2544,11 @@ fn.apply(context, args); lastTime = Date.now(); } - }, wait - (Date.now() - lastTime)); + }, Math.max(wait - (Date.now() - lastTime), 0)); } }; }; - var timeTaken = function timeTaken(callback) { - console.time('timeTaken'); - var r = callback(); - console.timeEnd('timeTaken'); - return r; - }; - var times = function times(n, fn) { var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var i = 0; @@ -2591,6 +2556,13 @@ while (fn.call(context, i) !== false && ++i < n) {} }; + var timeTaken = function timeTaken(callback) { + console.time('timeTaken'); + var r = callback(); + console.timeEnd('timeTaken'); + return r; + }; + var toCamelCase = function toCamelCase(str) { var s = 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.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase(); @@ -2610,6 +2582,10 @@ return num.toLocaleString('en-US'); }; + var toggleClass = function toggleClass(el, className) { + return el.classList.toggle(className); + }; + var toHash = function toHash(object, key) { return Array.prototype.reduce.call(object, function (acc, data, index) { return acc[!key ? index : data[key]] = data, acc; @@ -2622,6 +2598,14 @@ }).join('-'); }; + var tomorrow = function tomorrow() { + var long = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + var t = new Date(); + t.setDate(t.getDate() + 1); + var ret = "".concat(t.getFullYear(), "-").concat(String(t.getMonth() + 1).padStart(2, '0'), "-").concat(String(t.getDate()).padStart(2, '0')); + return !long ? ret : "".concat(ret, "T00:00:00"); + }; + var toOrdinalSuffix = function toOrdinalSuffix(num) { var int = parseInt(num), digits = [int % 10, int % 100], @@ -2641,18 +2625,6 @@ }).join('_'); }; - var toggleClass = function toggleClass(el, className) { - return el.classList.toggle(className); - }; - - var tomorrow = function tomorrow() { - var long = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - var t = new Date(); - t.setDate(t.getDate() + 1); - var ret = "".concat(t.getFullYear(), "-").concat(String(t.getMonth() + 1).padStart(2, '0'), "-").concat(String(t.getDate()).padStart(2, '0')); - return !long ? ret : "".concat(ret, "T00:00:00"); - }; - var transform = function transform(obj, fn, acc) { return Object.keys(obj).reduce(function (a, k) { return fn(a, obj[k], k, obj); @@ -2692,8 +2664,8 @@ }; }; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; + for (var _len50 = arguments.length, args = new Array(_len50), _key50 = 0; _key50 < _len50; _key50++) { + args[_key50] = arguments[_key50]; } if (n > args.length) throw new RangeError('Arguments too few!'); @@ -2742,9 +2714,7 @@ }; var unionBy = function unionBy(a, b, fn) { - var s = new Set(a.map(function (v) { - return fn(v); - })); + var s = new Set(a.map(fn)); return Array.from(new Set(_toConsumableArray(a).concat(_toConsumableArray(b.filter(function (x) { return !s.has(fn(x)); }))))); @@ -2789,7 +2759,7 @@ }; var untildify = function untildify(str) { - return str.replace(/^~($|\/|\\)/, "".concat(typeof require !== "undefined" && require('os').homedir(), "$1")); + return str.replace(/^~($|\/|\\)/, "".concat(require('os').homedir(), "$1")); }; var unzip = function unzip(arr) { @@ -2822,6 +2792,26 @@ }); }; + var URLJoin = function URLJoin() { + for (var _len51 = arguments.length, args = new Array(_len51), _key51 = 0; _key51 < _len51; _key51++) { + args[_key51] = arguments[_key51]; + } + + return args.join('/').replace(/[\/]+/g, '/').replace(/^(.+):\//, '$1://').replace(/^file:/, 'file:/').replace(/\/(\?|&|#[^!])/g, '$1').replace(/\?/g, '&').replace('&', '?'); + }; + + 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 UUIDGeneratorNode = function UUIDGeneratorNode() { + return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, function (c) { + return (c ^ crypto.randomBytes(1)[0] & 15 >> c / 4).toString(16); + }); + }; + var validateNumber = function validateNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; }; @@ -2833,8 +2823,8 @@ }; var without = function without(arr) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; + for (var _len52 = arguments.length, args = new Array(_len52 > 1 ? _len52 - 1 : 0), _key52 = 1; _key52 < _len52; _key52++) { + args[_key52 - 1] = arguments[_key52]; } return arr.filter(function (v) { @@ -2861,8 +2851,8 @@ }; var zip = function zip() { - for (var _len = arguments.length, arrays = new Array(_len), _key = 0; _key < _len; _key++) { - arrays[_key] = arguments[_key]; + for (var _len53 = arguments.length, arrays = new Array(_len53), _key53 = 0; _key53 < _len53; _key53++) { + arrays[_key53] = arguments[_key53]; } var maxLength = Math.max.apply(Math, _toConsumableArray(arrays.map(function (x) { @@ -2886,8 +2876,8 @@ }; var zipWith = function zipWith() { - for (var _len = arguments.length, array = new Array(_len), _key = 0; _key < _len; _key++) { - array[_key] = arguments[_key]; + for (var _len54 = arguments.length, array = new Array(_len54), _key54 = 0; _key54 < _len54; _key54++) { + array[_key54] = arguments[_key54]; } var fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined; @@ -2904,341 +2894,341 @@ }); }; - exports.CSVToArray = CSVToArray; - exports.CSVToJSON = CSVToJSON; - exports.JSONToFile = JSONToFile; - exports.JSONtoCSV = JSONtoCSV; - exports.RGBToHex = RGBToHex; - exports.URLJoin = URLJoin; - exports.UUIDGeneratorBrowser = UUIDGeneratorBrowser; - exports.UUIDGeneratorNode = UUIDGeneratorNode; - exports.all = all; - exports.allEqual = allEqual; - exports.any = any; - exports.approximatelyEqual = approximatelyEqual; - exports.arrayToCSV = arrayToCSV; - exports.arrayToHtmlList = arrayToHtmlList; - exports.ary = ary; - exports.atob = atob; - exports.attempt = attempt; - exports.average = average; - exports.averageBy = averageBy; - exports.bifurcate = bifurcate; - exports.bifurcateBy = bifurcateBy; - exports.bind = bind; - exports.bindAll = bindAll; - exports.bindKey = bindKey; - exports.binomialCoefficient = binomialCoefficient; - exports.bottomVisible = bottomVisible; - exports.btoa = btoa; - exports.byteSize = byteSize; - exports.call = call; - exports.capitalize = capitalize; - exports.capitalizeEveryWord = capitalizeEveryWord; - exports.castArray = castArray; - exports.chainAsync = chainAsync; - exports.chunk = chunk; - exports.clampNumber = clampNumber; - exports.cloneRegExp = cloneRegExp; - exports.coalesce = coalesce; - exports.coalesceFactory = coalesceFactory; - exports.collectInto = collectInto; - exports.colorize = colorize; - exports.compact = compact; - exports.compose = compose; - exports.composeRight = composeRight; - exports.converge = converge; - exports.copyToClipboard = copyToClipboard; - exports.countBy = countBy; - exports.countOccurrences = countOccurrences; - exports.counter = counter; - exports.createElement = createElement; - exports.createEventHub = createEventHub; - exports.currentURL = currentURL; - exports.curry = curry; - exports.dayOfYear = dayOfYear; - exports.debounce = debounce; - exports.decapitalize = decapitalize; - exports.deepClone = deepClone; - exports.deepFlatten = deepFlatten; - exports.deepFreeze = deepFreeze; - exports.defaults = defaults; - exports.defer = defer; - exports.degreesToRads = degreesToRads; - exports.delay = delay; - exports.detectDeviceType = detectDeviceType; - exports.difference = difference; - exports.differenceBy = differenceBy; - exports.differenceWith = differenceWith; - exports.dig = dig; - exports.digitize = digitize; - exports.distance = distance; - exports.drop = drop; - exports.dropRight = dropRight; - exports.dropRightWhile = dropRightWhile; - exports.dropWhile = dropWhile; - exports.elementContains = elementContains; - exports.elementIsVisibleInViewport = elementIsVisibleInViewport; - exports.elo = elo; - exports.equals = equals; - exports.escapeHTML = escapeHTML; - exports.escapeRegExp = escapeRegExp; - exports.everyNth = everyNth; - exports.extendHex = extendHex; - exports.factorial = factorial; - exports.fibonacci = fibonacci; - exports.filterNonUnique = filterNonUnique; - exports.filterNonUniqueBy = filterNonUniqueBy; - exports.findKey = findKey; - exports.findLast = findLast; - exports.findLastIndex = findLastIndex; - exports.findLastKey = findLastKey; - exports.flatten = flatten; - exports.flattenObject = flattenObject; - exports.flip = flip; - exports.forEachRight = forEachRight; - exports.forOwn = forOwn; - exports.forOwnRight = forOwnRight; - exports.formatDuration = formatDuration; - exports.fromCamelCase = fromCamelCase; - exports.functionName = functionName; - exports.functions = functions; - exports.gcd = gcd; - exports.geometricProgression = geometricProgression; - exports.get = get; - exports.getColonTimeFromDate = getColonTimeFromDate; - exports.getDaysDiffBetweenDates = getDaysDiffBetweenDates; - exports.getImages = getImages; - exports.getMeridiemSuffixOfInteger = getMeridiemSuffixOfInteger; - exports.getScrollPosition = getScrollPosition; - exports.getStyle = getStyle; - exports.getType = getType; - exports.getURLParameters = getURLParameters; - exports.groupBy = groupBy; - exports.hammingDistance = hammingDistance; - exports.hasClass = hasClass; - exports.hasFlags = hasFlags; - exports.hashBrowser = hashBrowser; - exports.hashNode = hashNode; - exports.head = head; - exports.hexToRGB = hexToRGB; - exports.hide = hide; - exports.httpGet = httpGet; - exports.httpPost = httpPost; - exports.httpsRedirect = httpsRedirect; - exports.hz = hz; - exports.inRange = inRange; - exports.indentString = indentString; - exports.indexOfAll = indexOfAll; - exports.initial = initial; - exports.initialize2DArray = initialize2DArray; - exports.initializeArrayWithRange = initializeArrayWithRange; - exports.initializeArrayWithRangeRight = initializeArrayWithRangeRight; - exports.initializeArrayWithValues = initializeArrayWithValues; - exports.initializeNDArray = initializeNDArray; - exports.insertAfter = insertAfter; - exports.insertBefore = insertBefore; - exports.intersection = intersection; - exports.intersectionBy = intersectionBy; - exports.intersectionWith = intersectionWith; - exports.invertKeyValues = invertKeyValues; - exports.is = is; - exports.isAbsoluteURL = isAbsoluteURL; - exports.isAfterDate = isAfterDate; - exports.isAnagram = isAnagram; - exports.isArrayLike = isArrayLike; - exports.isBeforeDate = isBeforeDate; - exports.isBoolean = isBoolean; - exports.isBrowser = isBrowser; - exports.isBrowserTabFocused = isBrowserTabFocused; - exports.isDivisible = isDivisible; - exports.isDuplexStream = isDuplexStream; - exports.isEmpty = isEmpty; - exports.isEven = isEven; - exports.isFunction = isFunction; - exports.isLowerCase = isLowerCase; - exports.isNil = isNil; - exports.isNull = isNull; - exports.isNumber = isNumber; - exports.isObject = isObject; - exports.isObjectLike = isObjectLike; - exports.isPlainObject = isPlainObject; - exports.isPrime = isPrime; - exports.isPrimitive = isPrimitive; - exports.isPromiseLike = isPromiseLike; - exports.isReadableStream = isReadableStream; - exports.isSameDate = isSameDate; - exports.isSorted = isSorted; - exports.isStream = isStream; - exports.isString = isString; - exports.isSymbol = isSymbol; - exports.isTravisCI = isTravisCI; - exports.isUndefined = isUndefined; - exports.isUpperCase = isUpperCase; - exports.isValidJSON = isValidJSON; - exports.isWritableStream = isWritableStream; - exports.join = join; - exports.last = last; - exports.lcm = lcm; - exports.longestItem = longestItem; - exports.lowercaseKeys = lowercaseKeys; - exports.luhnCheck = luhnCheck; - exports.mapKeys = mapKeys; - exports.mapObject = mapObject; - exports.mapString = mapString; - exports.mapValues = mapValues; - exports.mask = mask; - exports.matches = matches; - exports.matchesWith = matchesWith; - exports.maxBy = maxBy; - exports.maxDate = maxDate; - exports.maxN = maxN; - exports.median = median; - exports.memoize = memoize; - exports.merge = merge; - exports.minBy = minBy; - exports.minDate = minDate; - exports.minN = minN; - exports.mostPerformant = mostPerformant; - exports.negate = negate; - exports.nest = nest; - exports.nodeListToArray = nodeListToArray; - exports.none = none; - exports.nthArg = nthArg; - exports.nthElement = nthElement; - exports.objectFromPairs = objectFromPairs; - exports.objectToPairs = objectToPairs; - exports.observeMutations = observeMutations; - exports.off = off; - exports.offset = offset; - exports.omit = omit; - exports.omitBy = omitBy; - exports.on = on; - exports.onUserInputChange = onUserInputChange; - exports.once = once; - exports.orderBy = orderBy; - exports.over = over; - exports.overArgs = overArgs; - exports.pad = pad; - exports.palindrome = palindrome; - exports.parseCookie = parseCookie; - exports.partial = partial; - exports.partialRight = partialRight; - exports.partition = partition; - exports.percentile = percentile; - exports.permutations = permutations; - exports.pick = pick; - exports.pickBy = pickBy; - exports.pipeAsyncFunctions = pipeAsyncFunctions; - exports.pipeFunctions = pipeFunctions; - exports.pluralize = pluralize; - exports.powerset = powerset; - exports.prefix = prefix; - exports.prettyBytes = prettyBytes; - exports.primes = primes; - exports.promisify = promisify; - exports.pull = pull; - exports.pullAtIndex = pullAtIndex; - exports.pullAtValue = pullAtValue; - exports.pullBy = pullBy; - exports.radsToDegrees = radsToDegrees; - exports.randomHexColorCode = randomHexColorCode; - exports.randomIntArrayInRange = randomIntArrayInRange; - exports.randomIntegerInRange = randomIntegerInRange; - exports.randomNumberInRange = randomNumberInRange; - exports.readFileLines = readFileLines; - exports.rearg = rearg; - exports.recordAnimationFrames = recordAnimationFrames; - exports.redirect = redirect; - exports.reduceSuccessive = reduceSuccessive; - exports.reduceWhich = reduceWhich; - exports.reducedFilter = reducedFilter; - exports.reject = reject; - exports.remove = remove; - exports.removeNonASCII = removeNonASCII; - exports.renameKeys = renameKeys; - exports.reverseString = reverseString; - exports.round = round; - exports.runAsync = runAsync; - exports.runPromisesInSeries = runPromisesInSeries; - exports.sample = sample; - exports.sampleSize = sampleSize; - exports.scrollToTop = scrollToTop; - exports.sdbm = sdbm; - exports.serializeCookie = serializeCookie; - exports.setStyle = setStyle; - exports.shallowClone = shallowClone; - exports.shank = shank; - exports.show = show; - exports.shuffle = shuffle; - exports.similarity = similarity; - exports.size = size; - exports.sleep = sleep; - exports.smoothScroll = smoothScroll; - exports.sortCharactersInString = sortCharactersInString; - exports.sortedIndex = sortedIndex; - exports.sortedIndexBy = sortedIndexBy; - exports.sortedLastIndex = sortedLastIndex; - exports.sortedLastIndexBy = sortedLastIndexBy; - exports.splitLines = splitLines; - exports.spreadOver = spreadOver; - exports.stableSort = stableSort; - exports.standardDeviation = standardDeviation; - exports.stringPermutations = stringPermutations; - exports.stripHTMLTags = stripHTMLTags; - exports.sum = sum; - exports.sumBy = sumBy; - exports.sumPower = sumPower; - exports.symmetricDifference = symmetricDifference; - exports.symmetricDifferenceBy = symmetricDifferenceBy; - exports.symmetricDifferenceWith = symmetricDifferenceWith; - exports.tail = tail; - exports.take = take; - exports.takeRight = takeRight; - exports.takeRightWhile = takeRightWhile; - exports.takeWhile = takeWhile; - exports.throttle = throttle; - exports.timeTaken = timeTaken; - exports.times = times; - exports.toCamelCase = toCamelCase; - exports.toCurrency = toCurrency; - exports.toDecimalMark = toDecimalMark; - exports.toHash = toHash; - exports.toKebabCase = toKebabCase; - exports.toOrdinalSuffix = toOrdinalSuffix; - exports.toSafeInteger = toSafeInteger; - exports.toSnakeCase = toSnakeCase; - exports.toggleClass = toggleClass; - exports.tomorrow = tomorrow; - exports.transform = transform; - exports.triggerEvent = triggerEvent; - exports.truncateString = truncateString; - exports.truthCheckCollection = truthCheckCollection; - exports.unary = unary; - exports.uncurry = uncurry; - exports.unescapeHTML = unescapeHTML; - exports.unflattenObject = unflattenObject; - exports.unfold = unfold; - exports.union = union; - exports.unionBy = unionBy; - exports.unionWith = unionWith; - exports.uniqueElements = uniqueElements; - exports.uniqueElementsBy = uniqueElementsBy; - exports.uniqueElementsByRight = uniqueElementsByRight; - exports.uniqueSymmetricDifference = uniqueSymmetricDifference; - exports.untildify = untildify; - exports.unzip = unzip; - exports.unzipWith = unzipWith; - exports.validateNumber = validateNumber; - exports.when = when; - exports.without = without; - exports.words = words; - exports.xProd = xProd; - exports.yesNo = yesNo; - exports.zip = zip; - exports.zipObject = zipObject; - exports.zipWith = zipWith; - - Object.defineProperty(exports, '__esModule', { value: true }); + module.exports = { + all: all, + allEqual: allEqual, + any: any, + approximatelyEqual: approximatelyEqual, + arrayToCSV: arrayToCSV, + arrayToHtmlList: arrayToHtmlList, + ary: ary, + atob: atob, + attempt: attempt, + average: average, + averageBy: averageBy, + bifurcate: bifurcate, + bifurcateBy: bifurcateBy, + bind: bind, + bindAll: bindAll, + bindKey: bindKey, + binomialCoefficient: binomialCoefficient, + bottomVisible: bottomVisible, + btoa: btoa, + byteSize: byteSize, + call: call, + capitalize: capitalize, + capitalizeEveryWord: capitalizeEveryWord, + castArray: castArray, + chainAsync: chainAsync, + chunk: chunk, + clampNumber: clampNumber, + cloneRegExp: cloneRegExp, + coalesce: coalesce, + coalesceFactory: coalesceFactory, + collectInto: collectInto, + colorize: colorize, + compact: compact, + compose: compose, + composeRight: composeRight, + converge: converge, + copyToClipboard: copyToClipboard, + countBy: countBy, + counter: counter, + countOccurrences: countOccurrences, + createElement: createElement, + createEventHub: createEventHub, + CSVToArray: CSVToArray, + CSVToJSON: CSVToJSON, + currentURL: currentURL, + curry: curry, + dayOfYear: dayOfYear, + debounce: debounce, + decapitalize: decapitalize, + deepClone: deepClone, + deepFlatten: deepFlatten, + deepFreeze: deepFreeze, + defaults: defaults, + defer: defer, + degreesToRads: degreesToRads, + delay: delay, + detectDeviceType: detectDeviceType, + difference: difference, + differenceBy: differenceBy, + differenceWith: differenceWith, + dig: dig, + digitize: digitize, + distance: distance, + drop: drop, + dropRight: dropRight, + dropRightWhile: dropRightWhile, + dropWhile: dropWhile, + elementContains: elementContains, + elementIsVisibleInViewport: elementIsVisibleInViewport, + elo: elo, + equals: equals, + escapeHTML: escapeHTML, + escapeRegExp: escapeRegExp, + everyNth: everyNth, + extendHex: extendHex, + factorial: factorial, + fibonacci: fibonacci, + filterNonUnique: filterNonUnique, + filterNonUniqueBy: filterNonUniqueBy, + findKey: findKey, + findLast: findLast, + findLastIndex: findLastIndex, + findLastKey: findLastKey, + flatten: flatten, + flattenObject: flattenObject, + flip: flip, + forEachRight: forEachRight, + formatDuration: formatDuration, + forOwn: forOwn, + forOwnRight: forOwnRight, + fromCamelCase: fromCamelCase, + functionName: functionName, + functions: functions, + gcd: gcd, + geometricProgression: geometricProgression, + get: get, + getColonTimeFromDate: getColonTimeFromDate, + getDaysDiffBetweenDates: getDaysDiffBetweenDates, + getImages: getImages, + getMeridiemSuffixOfInteger: getMeridiemSuffixOfInteger, + getScrollPosition: getScrollPosition, + getStyle: getStyle, + getType: getType, + getURLParameters: getURLParameters, + groupBy: groupBy, + hammingDistance: hammingDistance, + hasClass: hasClass, + hasFlags: hasFlags, + hashBrowser: hashBrowser, + hashNode: hashNode, + head: head, + hexToRGB: hexToRGB, + hide: hide, + httpGet: httpGet, + httpPost: httpPost, + httpsRedirect: httpsRedirect, + hz: hz, + indentString: indentString, + indexOfAll: indexOfAll, + initial: initial, + initialize2DArray: initialize2DArray, + initializeArrayWithRange: initializeArrayWithRange, + initializeArrayWithRangeRight: initializeArrayWithRangeRight, + initializeArrayWithValues: initializeArrayWithValues, + initializeNDArray: initializeNDArray, + inRange: inRange, + insertAfter: insertAfter, + insertBefore: insertBefore, + intersection: intersection, + intersectionBy: intersectionBy, + intersectionWith: intersectionWith, + invertKeyValues: invertKeyValues, + is: is, + isAbsoluteURL: isAbsoluteURL, + isAfterDate: isAfterDate, + isAnagram: isAnagram, + isArrayLike: isArrayLike, + isBeforeDate: isBeforeDate, + isBoolean: isBoolean, + isBrowser: isBrowser, + isBrowserTabFocused: isBrowserTabFocused, + isDivisible: isDivisible, + isDuplexStream: isDuplexStream, + isEmpty: isEmpty, + isEven: isEven, + isFunction: isFunction, + isLowerCase: isLowerCase, + isNil: isNil, + isNull: isNull, + isNumber: isNumber, + isObject: isObject, + isObjectLike: isObjectLike, + isPlainObject: isPlainObject, + isPrime: isPrime, + isPrimitive: isPrimitive, + isPromiseLike: isPromiseLike, + isReadableStream: isReadableStream, + isSameDate: isSameDate, + isSorted: isSorted, + isStream: isStream, + isString: isString, + isSymbol: isSymbol, + isTravisCI: isTravisCI, + isUndefined: isUndefined, + isUpperCase: isUpperCase, + isValidJSON: isValidJSON, + isWritableStream: isWritableStream, + join: join, + JSONtoCSV: JSONtoCSV, + JSONToFile: JSONToFile, + last: last, + lcm: lcm, + longestItem: longestItem, + lowercaseKeys: lowercaseKeys, + luhnCheck: luhnCheck, + mapKeys: mapKeys, + mapObject: mapObject, + mapString: mapString, + mapValues: mapValues, + mask: mask, + matches: matches, + matchesWith: matchesWith, + maxBy: maxBy, + maxDate: maxDate, + maxN: maxN, + median: median, + memoize: memoize, + merge: merge, + minBy: minBy, + minDate: minDate, + minN: minN, + mostPerformant: mostPerformant, + negate: negate, + nest: nest, + nodeListToArray: nodeListToArray, + none: none, + nthArg: nthArg, + nthElement: nthElement, + objectFromPairs: objectFromPairs, + objectToPairs: objectToPairs, + observeMutations: observeMutations, + off: off, + offset: offset, + omit: omit, + omitBy: omitBy, + on: on, + once: once, + onUserInputChange: onUserInputChange, + orderBy: orderBy, + over: over, + overArgs: overArgs, + pad: pad, + palindrome: palindrome, + parseCookie: parseCookie, + partial: partial, + partialRight: partialRight, + partition: partition, + percentile: percentile, + permutations: permutations, + pick: pick, + pickBy: pickBy, + pipeAsyncFunctions: pipeAsyncFunctions, + pipeFunctions: pipeFunctions, + pluralize: pluralize, + powerset: powerset, + prefix: prefix, + prettyBytes: prettyBytes, + primes: primes, + promisify: promisify, + pull: pull, + pullAtIndex: pullAtIndex, + pullAtValue: pullAtValue, + pullBy: pullBy, + radsToDegrees: radsToDegrees, + randomHexColorCode: randomHexColorCode, + randomIntArrayInRange: randomIntArrayInRange, + randomIntegerInRange: randomIntegerInRange, + randomNumberInRange: randomNumberInRange, + readFileLines: readFileLines, + rearg: rearg, + recordAnimationFrames: recordAnimationFrames, + redirect: redirect, + reducedFilter: reducedFilter, + reduceSuccessive: reduceSuccessive, + reduceWhich: reduceWhich, + reject: reject, + remove: remove, + removeNonASCII: removeNonASCII, + renameKeys: renameKeys, + reverseString: reverseString, + RGBToHex: RGBToHex, + round: round, + runAsync: runAsync, + runPromisesInSeries: runPromisesInSeries, + sample: sample, + sampleSize: sampleSize, + scrollToTop: scrollToTop, + sdbm: sdbm, + serializeCookie: serializeCookie, + setStyle: setStyle, + shallowClone: shallowClone, + shank: shank, + show: show, + shuffle: shuffle, + similarity: similarity, + size: size, + sleep: sleep, + smoothScroll: smoothScroll, + sortCharactersInString: sortCharactersInString, + sortedIndex: sortedIndex, + sortedIndexBy: sortedIndexBy, + sortedLastIndex: sortedLastIndex, + sortedLastIndexBy: sortedLastIndexBy, + splitLines: splitLines, + spreadOver: spreadOver, + stableSort: stableSort, + standardDeviation: standardDeviation, + stringPermutations: stringPermutations, + stripHTMLTags: stripHTMLTags, + sum: sum, + sumBy: sumBy, + sumPower: sumPower, + symmetricDifference: symmetricDifference, + symmetricDifferenceBy: symmetricDifferenceBy, + symmetricDifferenceWith: symmetricDifferenceWith, + tail: tail, + take: take, + takeRight: takeRight, + takeRightWhile: takeRightWhile, + takeWhile: takeWhile, + throttle: throttle, + times: times, + timeTaken: timeTaken, + toCamelCase: toCamelCase, + toCurrency: toCurrency, + toDecimalMark: toDecimalMark, + toggleClass: toggleClass, + toHash: toHash, + toKebabCase: toKebabCase, + tomorrow: tomorrow, + toOrdinalSuffix: toOrdinalSuffix, + toSafeInteger: toSafeInteger, + toSnakeCase: toSnakeCase, + transform: transform, + triggerEvent: triggerEvent, + truncateString: truncateString, + truthCheckCollection: truthCheckCollection, + unary: unary, + uncurry: uncurry, + unescapeHTML: unescapeHTML, + unflattenObject: unflattenObject, + unfold: unfold, + union: union, + unionBy: unionBy, + unionWith: unionWith, + uniqueElements: uniqueElements, + uniqueElementsBy: uniqueElementsBy, + uniqueElementsByRight: uniqueElementsByRight, + uniqueSymmetricDifference: uniqueSymmetricDifference, + untildify: untildify, + unzip: unzip, + unzipWith: unzipWith, + URLJoin: URLJoin, + UUIDGeneratorBrowser: UUIDGeneratorBrowser, + UUIDGeneratorNode: UUIDGeneratorNode, + validateNumber: validateNumber, + when: when, + without: without, + words: words, + xProd: xProd, + yesNo: yesNo, + zip: zip, + zipObject: zipObject, + zipWith: zipWith + }; }))); diff --git a/dist/_30s.es5.min.js b/dist/_30s.es5.min.js index 8183db353..8b18cc1f8 100644 --- a/dist/_30s.es5.min.js +++ b/dist/_30s.es5.min.js @@ -1 +1 @@ -(function(e,t){'object'==typeof exports&&'undefined'!=typeof module?t(exports):'function'==typeof define&&define.amd?define(['exports'],t):t(e._30s={})})(this,function(e){'use strict';function t(e){return t='function'==typeof Symbol&&'symbol'==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&'function'==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?'symbol':typeof e},t(e)}function n(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function i(e){for(var t=1;t>e/4).toString(16)})},e.UUIDGeneratorNode=function(){return'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,function(e){return(e^x.randomBytes(1)[0]&15>>e/4).toString(16)})},e.all=function(e){var t=1'.concat(e,'')}).join('')}()},e.ary=function(e,t){return function(){for(var n=arguments.length,i=Array(n),r=0;rt||t>e)return 0;if(0===t||t===e)return 1;if(1===t||t===e-1)return e;e-t=(document.documentElement.scrollHeight||document.documentElement.clientHeight)},e.btoa=function(e){return Buffer.from(e,'binary').toString('base64')},e.byteSize=function(e){return new Blob([e]).size},e.call=function(e){for(var t=arguments.length,n=Array(1(n-t)*i?-i:i,o=setInterval(function(){a+=l,document.querySelector(e).innerHTML=a,a>=n&&(document.querySelector(e).innerHTML=n),a>=n&&clearInterval(o)},j(k(r/(n-t))));return o},e.createElement=function(e){var t=document.createElement('div');return t.innerHTML=e,t.firstElementChild},e.createEventHub=function(){return{hub:Object.create(null),emit:function(e,t){(this.hub[e]||[]).forEach(function(e){return e(t)})},on:function(e,t){this.hub[e]||(this.hub[e]=[]),this.hub[e].push(t)},off:function(e,t){var n=(this.hub[e]||[]).findIndex(function(e){return e===t});-1'"]/g,function(e){return{"&":'&',"<":'<',">":'>',"'":''','"':'"'}[e]||e})},e.escapeRegExp=function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')},e.everyNth=function(e,t){return e.filter(function(n,e){return e%t==t-1})},e.extendHex=function(e){return'#'+e.slice(e.startsWith('#')?1:0).split('').map(function(e){return e+e}).join('')},e.factorial=function e(t){return 0>t?function(){throw new TypeError('Negative numbers are not allowed!')}():1>=t?1:t*e(t-1)},e.fibonacci=function(e){return Array.from({length:e}).reduce(function(e,t,n){return e.concat(1e&&(e=-e);var t={day:k(e/864e5),hour:k(e/36e5)%24,minute:k(e/6e4)%60,second:k(e/1e3)%60,millisecond:k(e)%1e3};return Object.entries(t).filter(function(e){return 0!==e[1]}).map(function(e){var t=r(e,2),n=t[0],i=t[1];return''.concat(i,' ').concat(n).concat(1===i?'':'s')}).join(', ')},e.fromCamelCase=function(e){var t=1e?e%12+'am':e%12+'pm'},e.getScrollPosition=function(){var e=0>>(t?24:16))+', '+((n&(t?16711680:65280))>>>(t?16:8))+', '+((n&(t?65280:255))>>>(t?8:0))+(t?', '.concat(255&n):'')+')'},e.hide=function(e){return e.forEach(function(t){return t.style.display='none'})},e.httpGet=function(e,t){var n=2n){var i=[t,n];n=i[0],t=i[1]}return null==n?0<=e&&e=t&&et},e.isAnagram=function(e,t){var n=function(e){return e.toLowerCase().replace(/[^a-z0-9]/gi,'').split('').sort().join('')};return n(e)===n(t)},e.isArrayLike=function(e){return null!=e&&'function'==typeof e[Symbol.iterator]},e.isBeforeDate=function(e,t){return ee.length?t:e})},e.lowercaseKeys=function(e){return Object.keys(e).reduce(function(t,n){return t[n.toLowerCase()]=e[n],t},{})},e.luhnCheck=function(e){var t=(e+'').split('').reverse().map(function(e){return parseInt(e)}),n=t.splice(0,1)[0],i=t.reduce(function(e,t,n){return 0==n%2?e+2*t%9||9:e+t},0);return i+=n,0==i%10},e.mapKeys=function(e,t){return Object.keys(e).reduce(function(n,i){return n[t(e[i],i,e)]=e[i],n},{})},e.mapObject=function(e,t){return function(n){return n=[e,e.map(t)],n[0].reduce(function(e,t,i){return e[t]=n[1][i],e},{})}()},e.mapString=function(e,t){return e.split('').map(function(n,r){return t(n,r,e)}).join('')},e.mapValues=function(e,t){return Object.keys(e).reduce(function(n,i){return n[i]=t(e[i],i,e),n},{})},e.mask=function(e){var t=1r-n&&(t='mouse',e(t),document.removeEventListener('mousemove',i)),n=r};document.addEventListener('touchstart',function(){'touch'==t||(t='touch',e(t),document.addEventListener('mousemove',i))})},e.once=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,i=Array(n),r=0;rd?1:sj(e))return e+(i?' ':'')+r[0];var a=m(k(Math.log10(0>e?-e:e)/3),r.length-1),l=+((0>e?-e:e)/u(1e3,a)).toPrecision(t);return(0>e?'-':'')+l+(i?' ':'')+r[a]},e.primes=function(e){var t=Array.from({length:e-1}).map(function(e,t){return t+2}),n=k(g(e)),i=Array.from({length:n-1}).map(function(e,t){return t+2});return i.forEach(function(e){return t=t.filter(function(t){return 0!=t%e||t===e})}),t},e.promisify=function(e){return function(){for(var t=arguments.length,n=Array(t),i=0;ie[e.length-1],i=e.findIndex(function(e){return n?t>=e:t<=e});return-1===i?e.length:i},e.sortedIndexBy=function(e,t,n){var i=n(e[0])>n(e[e.length-1]),r=n(t),a=e.findIndex(function(e){return i?r>=n(e):r<=n(e)});return-1===a?e.length:a},e.sortedLastIndex=function(e,t){var n=e[0]>e[e.length-1],i=e.reverse().findIndex(function(e){return n?t<=e:t>=e});return-1===i?0:e.length-i},e.sortedLastIndexBy=function(e,t,n){var i=n(e[0])>n(e[e.length-1]),r=n(t),a=e.map(n).reverse().findIndex(function(e){return i?r<=e:r>=e});return-1===a?0:e.length-a},e.splitLines=function(e){return e.split(/\r?\n/)},e.spreadOver=function(e){return function(t){return e.apply(void 0,o(t))}},e.stableSort=function(e,t){return e.map(function(e,t){return{item:e,index:t}}).sort(function(e,n){return t(e.item,n.item)||e.index-n.index}).map(function(e){var t=e.item;return t})},e.standardDeviation=function(e){var t=!!(1=t.length?2===t.length?[t,t[1]+t[0]]:[t]:t.split('').reduce(function(n,r,a){return n.concat(e(t.slice(0,a)+t.slice(a+1)).map(function(e){return r+e}))},[])},e.stripHTMLTags=function(e){return e.replace(/<[^>]*>/g,'')},e.sum=function(){for(var e=arguments.length,t=Array(e),n=0;n=t&&(e.apply(a,l),r=Date.now())},t-(Date.now()-r))):(e.apply(a,l),r=Date.now(),n=!0)}},e.timeTaken=function(e){console.time('timeTaken');var t=e();return console.timeEnd('timeTaken'),t},e.times=function(e,t){for(var n=2t?e.slice(0,3r.length)throw new RangeError('Arguments too few!');return n(e)(r.slice(0,t))}},e.unescapeHTML=function(e){return e.replace(/&|<|>|'|"/g,function(e){return{"&":'&',"<":'<',">":'>',"'":'\'',""":'"'}[e]||e})},e.unflattenObject=function(e){return Object.keys(e).reduce(function(t,n){if(-1!==n.indexOf('.')){var r=n.split('.');Object.assign(t,JSON.parse('{'+r.map(function(e,t){return t===r.length-1?'"'.concat(e,'":'):'"'.concat(e,'":{')}).join('')+e[n]+'}'.repeat(r.length)))}else t[n]=e[n];return t},{})},e.unfold=function(e,t){for(var n=[],i=[null,t];i=e(i[1]);)n.push(i[0]);return n},e.union=function(e,t){return Array.from(new Set(o(e).concat(o(t))))},e.unionBy=function(e,t,n){var i=new Set(e.map(function(e){return n(e)}));return Array.from(new Set(o(e).concat(o(t.filter(function(e){return!i.has(n(e))})))))},e.unionWith=function(e,t,n){return Array.from(new Set(o(e).concat(o(t.filter(function(t){return-1===e.findIndex(function(e){return n(t,e)})})))))},e.uniqueElements=function(e){return o(new Set(e))},e.uniqueElementsBy=function(e,t){return e.reduce(function(e,n){return e.some(function(e){return t(n,e)})||e.push(n),e},[])},e.uniqueElementsByRight=function(e,t){return e.reduceRight(function(e,n){return e.some(function(e){return t(n,e)})||e.push(n),e},[])},e.uniqueSymmetricDifference=function(e,t){return o(new Set(o(e.filter(function(e){return!t.includes(e)})).concat(o(t.filter(function(t){return!e.includes(t)})))))},e.untildify=function(e){return e.replace(/^~($|\/|\\)/,''.concat('undefined'!=typeof require&&require('os').homedir(),'$1'))},e.unzip=function(e){return e.reduce(function(e,t){return t.forEach(function(t,n){return e[n].push(t)}),e},Array.from({length:_.apply(Math,o(e.map(function(e){return e.length})))}).map(function(){return[]}))},e.unzipWith=function(e,t){return e.reduce(function(e,t){return t.forEach(function(t,n){return e[n].push(t)}),e},Array.from({length:_.apply(Math,o(e.map(function(e){return e.length})))}).map(function(){return[]})).map(function(e){return t.apply(void 0,o(e))})},e.validateNumber=function(e){return!isNaN(parseFloat(e))&&isFinite(e)&&+e==e},e.when=function(e,t){return function(n){return e(n)?t(n):n}},e.without=function(e){for(var t=arguments.length,n=Array(1'.concat(e,'')}).join('')}()},ary:function(e,t){return function(){for(var n=arguments.length,i=Array(n),r=0;rt||t>e)return 0;if(0===t||t===e)return 1;if(1===t||t===e-1)return e;e-t=(document.documentElement.scrollHeight||document.documentElement.clientHeight)},btoa:function(e){return Buffer.from(e,'binary').toString('base64')},byteSize:function(e){return new Blob([e]).size},call:function(e){for(var t=arguments.length,n=Array(1(n-t)*i?-i:i,o=setInterval(function(){a+=l,document.querySelector(e).innerHTML=a,a>=n&&(document.querySelector(e).innerHTML=n),a>=n&&clearInterval(o)},v(y(r/(n-t))));return o},countOccurrences:function(e,t){return e.reduce(function(e,n){return n===t?e+1:e},0)},createElement:function(e){var t=document.createElement('div');return t.innerHTML=e,t.firstElementChild},createEventHub:function(){return{hub:Object.create(null),emit:function(e,t){(this.hub[e]||[]).forEach(function(e){return e(t)})},on:function(e,t){this.hub[e]||(this.hub[e]=[]),this.hub[e].push(t)},off:function(e,t){var n=(this.hub[e]||[]).findIndex(function(e){return e===t});-1'"]/g,function(e){return{"&":'&',"<":'<',">":'>',"'":''','"':'"'}[e]||e})},escapeRegExp:function(e){return e.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')},everyNth:function(e,t){return e.filter(function(n,e){return e%t==t-1})},extendHex:function(e){return'#'+e.slice(e.startsWith('#')?1:0).split('').map(function(e){return e+e}).join('')},factorial:function e(t){return 0>t?function(){throw new TypeError('Negative numbers are not allowed!')}():1>=t?1:t*e(t-1)},fibonacci:function(e){return Array.from({length:e}).reduce(function(e,t,n){return e.concat(1e&&(e=-e);var t={day:y(e/864e5),hour:y(e/36e5)%24,minute:y(e/6e4)%60,second:y(e/1e3)%60,millisecond:y(e)%1e3};return Object.entries(t).filter(function(e){return 0!==e[1]}).map(function(e){var t=r(e,2),n=t[0],i=t[1];return''.concat(i,' ').concat(n).concat(1===i?'':'s')}).join(', ')},forOwn:function(e,t){return Object.keys(e).forEach(function(n){return t(e[n],n,e)})},forOwnRight:function(e,t){return Object.keys(e).reverse().forEach(function(n){return t(e[n],n,e)})},fromCamelCase:function(e){var t=1e?e%12+'am':e%12+'pm'},getScrollPosition:function(){var e=0>>(t?24:16))+', '+((n&(t?16711680:65280))>>>(t?16:8))+', '+((n&(t?65280:255))>>>(t?8:0))+(t?', '.concat(255&n):'')+')'},hide:function(e){return e.forEach(function(t){return t.style.display='none'})},httpGet:function(e,t){var n=2n){var i=[t,n];n=i[0],t=i[1]}return null==n?0<=e&&e=t&&et},isAnagram:function(e,t){var n=function(e){return e.toLowerCase().replace(/[^a-z0-9]/gi,'').split('').sort().join('')};return n(e)===n(t)},isArrayLike:function(e){return null!=e&&'function'==typeof e[Symbol.iterator]},isBeforeDate:function(e,t){return ee.length?t:e})},lowercaseKeys:function(e){return Object.keys(e).reduce(function(t,n){return t[n.toLowerCase()]=e[n],t},{})},luhnCheck:function(e){var t=(e+'').split('').reverse().map(function(e){return parseInt(e)}),n=t.splice(0,1)[0],i=t.reduce(function(e,t,n){return 0==n%2?e+2*t%9||9:e+t},0);return i+=n,0==i%10},mapKeys:function(e,t){return Object.keys(e).reduce(function(n,i){return n[t(e[i],i,e)]=e[i],n},{})},mapObject:function(e,t){return function(n){return n=[e,e.map(t)],n[0].reduce(function(e,t,i){return e[t]=n[1][i],e},{})}()},mapString:function(e,t){return e.split('').map(function(n,r){return t(n,r,e)}).join('')},mapValues:function(e,t){return Object.keys(e).reduce(function(n,i){return n[i]=t(e[i],i,e),n},{})},mask:function(e){var t=1r-n&&(t='mouse',e(t),document.removeEventListener('mousemove',i)),n=r};document.addEventListener('touchstart',function(){'touch'==t||(t='touch',e(t),document.addEventListener('mousemove',i))})},orderBy:function(e,t,n){return o(e).sort(function(e,a){return t.reduce(function(t,l,o){if(0===t){var i=n&&'desc'===n[o]?[a[l],e[l]]:[e[l],a[l]],c=r(i,2),s=c[0],d=c[1];t=s>d?1:sv(e))return e+(i?' ':'')+r[0];var a=m(y(Math.log10(0>e?-e:e)/3),r.length-1),l=+((0>e?-e:e)/g(1e3,a)).toPrecision(t);return(0>e?'-':'')+l+(i?' ':'')+r[a]},primes:function(e){var t=Array.from({length:e-1}).map(function(e,t){return t+2}),n=y(h(e)),i=Array.from({length:n-1}).map(function(e,t){return t+2});return i.forEach(function(e){return t=t.filter(function(t){return 0!=t%e||t===e})}),t},promisify:function(e){return function(){for(var t=arguments.length,n=Array(t),i=0;ie[e.length-1],i=e.findIndex(function(e){return n?t>=e:t<=e});return-1===i?e.length:i},sortedIndexBy:function(e,t,n){var i=n(e[0])>n(e[e.length-1]),r=n(t),a=e.findIndex(function(e){return i?r>=n(e):r<=n(e)});return-1===a?e.length:a},sortedLastIndex:function(e,t){var n=e[0]>e[e.length-1],i=e.reverse().findIndex(function(e){return n?t<=e:t>=e});return-1===i?0:e.length-i},sortedLastIndexBy:function(e,t,n){var i=n(e[0])>n(e[e.length-1]),r=n(t),a=e.map(n).reverse().findIndex(function(e){return i?r<=e:r>=e});return-1===a?0:e.length-a},splitLines:function(e){return e.split(/\r?\n/)},spreadOver:function(e){return function(t){return e.apply(void 0,o(t))}},stableSort:function(e,t){return e.map(function(e,t){return{item:e,index:t}}).sort(function(e,n){return t(e.item,n.item)||e.index-n.index}).map(function(e){var t=e.item;return t})},standardDeviation:function(e){var t=!!(1=t.length?2===t.length?[t,t[1]+t[0]]:[t]:t.split('').reduce(function(n,r,a){return n.concat(e(t.slice(0,a)+t.slice(a+1)).map(function(e){return r+e}))},[])},stripHTMLTags:function(e){return e.replace(/<[^>]*>/g,'')},sum:function(){for(var e=arguments.length,t=Array(e),n=0;n=t&&(e.apply(a,l),r=Date.now())},k(t-(Date.now()-r),0))):(e.apply(a,l),r=Date.now(),n=!0)}},times:function(e,t){for(var n=2t?e.slice(0,3r.length)throw new RangeError('Arguments too few!');return n(e)(r.slice(0,t))}},unescapeHTML:function(e){return e.replace(/&|<|>|'|"/g,function(e){return{"&":'&',"<":'<',">":'>',"'":'\'',""":'"'}[e]||e})},unflattenObject:function(e){return Object.keys(e).reduce(function(t,n){if(-1!==n.indexOf('.')){var r=n.split('.');Object.assign(t,JSON.parse('{'+r.map(function(e,t){return t===r.length-1?'"'.concat(e,'":'):'"'.concat(e,'":{')}).join('')+e[n]+'}'.repeat(r.length)))}else t[n]=e[n];return t},{})},unfold:function(e,t){for(var n=[],i=[null,t];i=e(i[1]);)n.push(i[0]);return n},union:function(e,t){return Array.from(new Set(o(e).concat(o(t))))},unionBy:function(e,t,n){var i=new Set(e.map(n));return Array.from(new Set(o(e).concat(o(t.filter(function(e){return!i.has(n(e))})))))},unionWith:function(e,t,n){return Array.from(new Set(o(e).concat(o(t.filter(function(t){return-1===e.findIndex(function(e){return n(t,e)})})))))},uniqueElements:function(e){return o(new Set(e))},uniqueElementsBy:function(e,t){return e.reduce(function(e,n){return e.some(function(e){return t(n,e)})||e.push(n),e},[])},uniqueElementsByRight:function(e,t){return e.reduceRight(function(e,n){return e.some(function(e){return t(n,e)})||e.push(n),e},[])},uniqueSymmetricDifference:function(e,t){return o(new Set(o(e.filter(function(e){return!t.includes(e)})).concat(o(t.filter(function(t){return!e.includes(t)})))))},untildify:function(e){return e.replace(/^~($|\/|\\)/,''.concat(require('os').homedir(),'$1'))},unzip:function(e){return e.reduce(function(e,t){return t.forEach(function(t,n){return e[n].push(t)}),e},Array.from({length:k.apply(Math,o(e.map(function(e){return e.length})))}).map(function(){return[]}))},unzipWith:function(e,t){return e.reduce(function(e,t){return t.forEach(function(t,n){return e[n].push(t)}),e},Array.from({length:k.apply(Math,o(e.map(function(e){return e.length})))}).map(function(){return[]})).map(function(e){return t.apply(void 0,o(e))})},URLJoin:function(){for(var e=arguments.length,t=Array(e),n=0;n>e/4).toString(16)})},UUIDGeneratorNode:function(){return'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,function(e){return(e^S.randomBytes(1)[0]&15>>e/4).toString(16)})},validateNumber:function(e){return!isNaN(parseFloat(e))&&isFinite(e)&&+e==e},when:function(e,t){return function(n){return e(n)?t(n):n}},without:function(e){for(var t=arguments.length,n=Array(1 - data - .slice(omitFirstRow ? data.indexOf('\n') + 1 : 0) - .split('\n') - .map(v => v.split(delimiter)); - -const CSVToJSON = (data, delimiter = ',') => { - const titles = data.slice(0, data.indexOf('\n')).split(delimiter); - return data - .slice(data.indexOf('\n') + 1) - .split('\n') - .map(v => { - const values = v.split(delimiter); - return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {}); - }); -}; - +const crypto = typeof require !== "undefined" && require('crypto'); const fs = typeof require !== "undefined" && require('fs'); -const JSONToFile = (obj, filename) => - fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); - -const JSONtoCSV = (arr, columns, delimiter = ',') => - [ - columns.join(delimiter), - ...arr.map(obj => - columns.reduce( - (acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`, - '' - ) - ) - ].join('\n'); - -const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); - -const URLJoin = (...args) => - args - .join('/') - .replace(/[\/]+/g, '/') - .replace(/^(.+):\//, '$1://') - .replace(/^file:/, 'file:/') - .replace(/\/(\?|&|#[^!])/g, '$1') - .replace(/\?/g, '&') - .replace('&', '?'); - -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 all = (arr, fn = Boolean) => arr.every(fn); - -const allEqual = arr => arr.every(val => val === arr[0]); - -const any = (arr, fn = Boolean) => arr.some(fn); - -const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon; - -const arrayToCSV = (arr, delimiter = ',') => - arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n'); - -const arrayToHtmlList = (arr, listID) => - (el => ( - (el = document.querySelector('#' + listID)), - (el.innerHTML += arr.map(item => `
  • ${item}
  • `).join('')) - ))(); - -const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); - -const atob = str => Buffer.from(str, 'base64').toString('binary'); - -const attempt = (fn, ...args) => { - try { - return fn(...args); - } catch (e) { - return e instanceof Error ? e : new Error(e); - } -}; - -const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length; - -const averageBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) / - arr.length; - -const bifurcate = (arr, filter) => - arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]); - -const bifurcateBy = (arr, fn) => - arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]); - -const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]); - -const bindAll = (obj, ...fns) => - fns.forEach( - fn => ( - (f = obj[fn]), - (obj[fn] = function() { - return f.apply(obj); - }) - ) - ); - -const bindKey = (context, fn, ...boundArgs) => (...args) => - context[fn].apply(context, [...boundArgs, ...args]); - -const binomialCoefficient = (n, k) => { - if (Number.isNaN(n) || Number.isNaN(k)) return NaN; - if (k < 0 || k > n) return 0; - if (k === 0 || k === n) return 1; - if (k === 1 || k === n - 1) return n; - if (n - k < k) k = n - k; - let res = n; - for (let j = 2; j <= k; j++) res *= (n - j + 1) / j; - return Math.round(res); -}; - -const bottomVisible = () => - document.documentElement.clientHeight + window.scrollY >= - (document.documentElement.scrollHeight || document.documentElement.clientHeight); - -const btoa = str => Buffer.from(str, 'binary').toString('base64'); - -const byteSize = str => new Blob([str]).size; + const all = (arr, fn = Boolean) => arr.every(fn); + const allEqual = arr => arr.every(val => val === arr[0]); + const any = (arr, fn = Boolean) => arr.some(fn); + const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon; + const arrayToCSV = (arr, delimiter = ',') => + arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n'); + const arrayToHtmlList = (arr, listID) => + (el => ( + (el = document.querySelector('#' + listID)), + (el.innerHTML += arr.map(item => `
  • ${item}
  • `).join('')) + ))(); + const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); + const atob = str => Buffer.from(str, 'base64').toString('binary'); + const attempt = (fn, ...args) => { + try { + return fn(...args); + } catch (e) { + return e instanceof Error ? e : new Error(e); + } +}; + const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length; + const averageBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) / + arr.length; + const bifurcate = (arr, filter) => + arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]); + const bifurcateBy = (arr, fn) => + arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]); + const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]); + const bindAll = (obj, ...fns) => + fns.forEach( + fn => ( + (f = obj[fn]), + (obj[fn] = function() { + return f.apply(obj); + }) + ) + ); + const bindKey = (context, fn, ...boundArgs) => (...args) => + context[fn].apply(context, [...boundArgs, ...args]); + const binomialCoefficient = (n, k) => { + if (Number.isNaN(n) || Number.isNaN(k)) return NaN; + if (k < 0 || k > n) return 0; + if (k === 0 || k === n) return 1; + if (k === 1 || k === n - 1) return n; + if (n - k < k) k = n - k; + let res = n; + for (let j = 2; j <= k; j++) res *= (n - j + 1) / j; + return Math.round(res); +}; + const bottomVisible = () => + document.documentElement.clientHeight + window.scrollY >= + (document.documentElement.scrollHeight || document.documentElement.clientHeight); + const btoa = str => Buffer.from(str, 'binary').toString('base64'); + const byteSize = str => new Blob([str]).size; const call = (key, ...args) => context => context[key](...args); - -const capitalize = ([first, ...rest], lowerRest = false) => - first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); - -const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); - -const castArray = val => (Array.isArray(val) ? val : [val]); - -const chainAsync = fns => { - let curr = 0; - const next = () => fns[curr++](next); - next(); -}; - -const chunk = (arr, size) => - Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => - arr.slice(i * size, i * size + size) - ); - -const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); - -const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags); - -const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); - -const coalesceFactory = valid => (...args) => args.find(valid); - + const capitalize = ([first, ...rest], lowerRest = false) => + first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); + const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); + const castArray = val => (Array.isArray(val) ? val : [val]); + const chainAsync = fns => { + let curr = 0; + const next = () => fns[curr++](next); + next(); +}; + const chunk = (arr, size) => + Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => + arr.slice(i * size, i * size + size) + ); + const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); + const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags); + const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); + const coalesceFactory = valid => (...args) => args.find(valid); const collectInto = fn => (...args) => fn(args); - -const colorize = (...args) => ({ - black: `\x1b[30m${args.join(' ')}`, - red: `\x1b[31m${args.join(' ')}`, - green: `\x1b[32m${args.join(' ')}`, - yellow: `\x1b[33m${args.join(' ')}`, - blue: `\x1b[34m${args.join(' ')}`, - magenta: `\x1b[35m${args.join(' ')}`, - cyan: `\x1b[36m${args.join(' ')}`, - white: `\x1b[37m${args.join(' ')}`, - bgBlack: `\x1b[40m${args.join(' ')}\x1b[0m`, - bgRed: `\x1b[41m${args.join(' ')}\x1b[0m`, - bgGreen: `\x1b[42m${args.join(' ')}\x1b[0m`, - bgYellow: `\x1b[43m${args.join(' ')}\x1b[0m`, - bgBlue: `\x1b[44m${args.join(' ')}\x1b[0m`, - bgMagenta: `\x1b[45m${args.join(' ')}\x1b[0m`, - bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`, - bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m` -}); - -const compact = arr => arr.filter(Boolean); - -const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); - -const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); - -const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args))); - -const copyToClipboard = str => { - const el = document.createElement('textarea'); - el.value = str; - el.setAttribute('readonly', ''); - el.style.position = 'absolute'; - el.style.left = '-9999px'; - document.body.appendChild(el); - const selected = - document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; - el.select(); - document.execCommand('copy'); - document.body.removeChild(el); - if (selected) { - document.getSelection().removeAllRanges(); - document.getSelection().addRange(selected); - } -}; - -const countBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { - acc[val] = (acc[val] || 0) + 1; - return acc; - }, {}); - -const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); - -const counter = (selector, start, end, step = 1, duration = 2000) => { - let current = start, - _step = (end - start) * step < 0 ? -step : step, - timer = setInterval(() => { - current += _step; - document.querySelector(selector).innerHTML = current; - if (current >= end) document.querySelector(selector).innerHTML = end; - if (current >= end) clearInterval(timer); - }, Math.abs(Math.floor(duration / (end - start)))); - return timer; -}; - -const createElement = str => { - const el = document.createElement('div'); - el.innerHTML = str; - return el.firstElementChild; -}; - -const createEventHub = () => ({ - hub: Object.create(null), - emit(event, data) { - (this.hub[event] || []).forEach(handler => handler(data)); - }, - on(event, handler) { - if (!this.hub[event]) this.hub[event] = []; - this.hub[event].push(handler); - }, - off(event, handler) { - const i = (this.hub[event] || []).findIndex(h => h === handler); - if (i > -1) this.hub[event].splice(i, 1); - } -}); - -const currentURL = () => window.location.href; - -const curry = (fn, arity = fn.length, ...args) => - arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args); - -const dayOfYear = date => - Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); - -const debounce = (fn, ms = 0) => { - let timeoutId; - return function(...args) { - clearTimeout(timeoutId); - timeoutId = setTimeout(() => fn.apply(this, args), ms); - }; -}; - -const decapitalize = ([first, ...rest], upperRest = false) => - first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join('')); - -const deepClone = obj => { - let clone = Object.assign({}, obj); - Object.keys(clone).forEach( - key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]) - ); - return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone; -}; - -const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); - -const deepFreeze = obj => - Object.keys(obj).forEach( - prop => - !obj[prop] instanceof Object || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop]) - ) || Object.freeze(obj); - -const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); - -const defer = (fn, ...args) => setTimeout(fn, 1, ...args); - -const degreesToRads = deg => (deg * Math.PI) / 180.0; - -const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args); - -const detectDeviceType = () => - /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) - ? 'Mobile' - : 'Desktop'; - -const difference = (a, b) => { - const s = new Set(b); - return a.filter(x => !s.has(x)); -}; - -const differenceBy = (a, b, fn) => { - const s = new Set(b.map(v => fn(v))); - return a.filter(x => !s.has(fn(x))); -}; - -const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1); - -const dig = (obj, target) => - target in obj - ? obj[target] - : Object.values(obj).reduce((acc, val) => { - if (acc !== undefined) return acc; - if (typeof val === 'object') return dig(val, target); - }, undefined); - -const digitize = n => [...`${n}`].map(i => parseInt(i)); - -const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); - -const drop = (arr, n = 1) => arr.slice(n); - -const dropRight = (arr, n = 1) => arr.slice(0, -n); - -const dropRightWhile = (arr, func) => { - while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1); - return arr; -}; - -const dropWhile = (arr, func) => { - while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); - return arr; -}; - -const elementContains = (parent, child) => parent !== child && parent.contains(child); - -const elementIsVisibleInViewport = (el, partiallyVisible = false) => { - const { top, left, bottom, right } = el.getBoundingClientRect(); - const { innerHeight, innerWidth } = window; - return partiallyVisible - ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && - ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) - : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; -}; - -const elo = ([...ratings], kFactor = 32, selfRating) => { - const [a, b] = ratings; - const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400)); - const newRating = (rating, i) => - (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a)); - if (ratings.length === 2) { - return [newRating(a, 1), newRating(b, 0)]; - } - for (let i = 0, len = ratings.length; i < len; i++) { - let j = i; - while (j < len - 1) { - j++; - [ratings[i], ratings[j]] = elo([ratings[i], ratings[j]], kFactor); - } - } - return ratings; -}; - -const equals = (a, b) => { - if (a === b) return true; - if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime(); - if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b; - if (a === null || a === undefined || b === null || b === undefined) return false; - if (a.prototype !== b.prototype) return false; - let keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) return false; - return keys.every(k => equals(a[k], b[k])); -}; - -const escapeHTML = str => - str.replace( - /[&<>'"]/g, - tag => - ({ - '&': '&', - '<': '<', - '>': '>', - "'": ''', - '"': '"' - }[tag] || tag) - ); - -const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - -const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); - -const extendHex = shortHex => - '#' + - shortHex - .slice(shortHex.startsWith('#') ? 1 : 0) - .split('') - .map(x => x + x) - .join(''); - -const factorial = n => - n < 0 - ? (() => { - throw new TypeError('Negative numbers are not allowed!'); - })() - : n <= 1 - ? 1 - : n * factorial(n - 1); - -const fibonacci = n => - Array.from({ length: n }).reduce( - (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), - [] - ); - -const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); - -const filterNonUniqueBy = (arr, fn) => - arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j))); - -const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj)); - -const findLast = (arr, fn) => arr.filter(fn).pop(); - -const findLastIndex = (arr, fn) => - arr - .map((val, i) => [i, val]) - .filter(([i, val]) => fn(val, i, arr)) - .pop()[0]; - -const findLastKey = (obj, fn) => - Object.keys(obj) - .reverse() - .find(key => fn(obj[key], key, obj)); - -const flatten = (arr, depth = 1) => - arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []); - -const flattenObject = (obj, prefix = '') => - Object.keys(obj).reduce((acc, k) => { - const pre = prefix.length ? prefix + '.' : ''; - if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k)); - else acc[pre + k] = obj[k]; - return acc; - }, {}); - + const colorize = (...args) => ({ + black: `\x1b[30m${args.join(' ')}`, + red: `\x1b[31m${args.join(' ')}`, + green: `\x1b[32m${args.join(' ')}`, + yellow: `\x1b[33m${args.join(' ')}`, + blue: `\x1b[34m${args.join(' ')}`, + magenta: `\x1b[35m${args.join(' ')}`, + cyan: `\x1b[36m${args.join(' ')}`, + white: `\x1b[37m${args.join(' ')}`, + bgBlack: `\x1b[40m${args.join(' ')}\x1b[0m`, + bgRed: `\x1b[41m${args.join(' ')}\x1b[0m`, + bgGreen: `\x1b[42m${args.join(' ')}\x1b[0m`, + bgYellow: `\x1b[43m${args.join(' ')}\x1b[0m`, + bgBlue: `\x1b[44m${args.join(' ')}\x1b[0m`, + bgMagenta: `\x1b[45m${args.join(' ')}\x1b[0m`, + bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`, + bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m` +}); + const compact = arr => arr.filter(Boolean); + const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); + const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); + const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args))); + const copyToClipboard = str => { + const el = document.createElement('textarea'); + el.value = str; + el.setAttribute('readonly', ''); + el.style.position = 'absolute'; + el.style.left = '-9999px'; + document.body.appendChild(el); + const selected = + document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; + el.select(); + document.execCommand('copy'); + document.body.removeChild(el); + if (selected) { + document.getSelection().removeAllRanges(); + document.getSelection().addRange(selected); + } +}; + const countBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => { + acc[val] = (acc[val] || 0) + 1; + return acc; + }, {}); + const counter = (selector, start, end, step = 1, duration = 2000) => { + let current = start, + _step = (end - start) * step < 0 ? -step : step, + timer = setInterval(() => { + current += _step; + document.querySelector(selector).innerHTML = current; + if (current >= end) document.querySelector(selector).innerHTML = end; + if (current >= end) clearInterval(timer); + }, Math.abs(Math.floor(duration / (end - start)))); + return timer; +}; + const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); + const createElement = str => { + const el = document.createElement('div'); + el.innerHTML = str; + return el.firstElementChild; +}; + const createEventHub = () => ({ + hub: Object.create(null), + emit(event, data) { + (this.hub[event] || []).forEach(handler => handler(data)); + }, + on(event, handler) { + if (!this.hub[event]) this.hub[event] = []; + this.hub[event].push(handler); + }, + off(event, handler) { + const i = (this.hub[event] || []).findIndex(h => h === handler); + if (i > -1) this.hub[event].splice(i, 1); + } +}); + const CSVToArray = (data, delimiter = ',', omitFirstRow = false) => + data + .slice(omitFirstRow ? data.indexOf('\n') + 1 : 0) + .split('\n') + .map(v => v.split(delimiter)); + const CSVToJSON = (data, delimiter = ',') => { + const titles = data.slice(0, data.indexOf('\n')).split(delimiter); + return data + .slice(data.indexOf('\n') + 1) + .split('\n') + .map(v => { + const values = v.split(delimiter); + return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {}); + }); +}; + const currentURL = () => window.location.href; + const curry = (fn, arity = fn.length, ...args) => + arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args); + const dayOfYear = date => + Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); + const debounce = (fn, ms = 0) => { + let timeoutId; + return function(...args) { + clearTimeout(timeoutId); + timeoutId = setTimeout(() => fn.apply(this, args), ms); + }; +}; + const decapitalize = ([first, ...rest], upperRest = false) => + first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join('')); + const deepClone = obj => { + let clone = Object.assign({}, obj); + Object.keys(clone).forEach( + key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]) + ); + return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone; +}; + const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); + const deepFreeze = obj => + Object.keys(obj).forEach( + prop => + !(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop]) + ) || Object.freeze(obj); + const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); + const defer = (fn, ...args) => setTimeout(fn, 1, ...args); + const degreesToRads = deg => (deg * Math.PI) / 180.0; + const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args); + const detectDeviceType = () => + /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) + ? 'Mobile' + : 'Desktop'; + const difference = (a, b) => { + const s = new Set(b); + return a.filter(x => !s.has(x)); +}; + const differenceBy = (a, b, fn) => { + const s = new Set(b.map(fn)); + return a.filter(x => !s.has(fn(x))); +}; + const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1); + const dig = (obj, target) => + target in obj + ? obj[target] + : Object.values(obj).reduce((acc, val) => { + if (acc !== undefined) return acc; + if (typeof val === 'object') return dig(val, target); + }, undefined); + const digitize = n => [...`${n}`].map(i => parseInt(i)); + const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); + const drop = (arr, n = 1) => arr.slice(n); + const dropRight = (arr, n = 1) => arr.slice(0, -n); + const dropRightWhile = (arr, func) => { + while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1); + return arr; +}; + const dropWhile = (arr, func) => { + while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); + return arr; +}; + const elementContains = (parent, child) => parent !== child && parent.contains(child); + const elementIsVisibleInViewport = (el, partiallyVisible = false) => { + const { top, left, bottom, right } = el.getBoundingClientRect(); + const { innerHeight, innerWidth } = window; + return partiallyVisible + ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && + ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) + : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; +}; + const elo = ([...ratings], kFactor = 32, selfRating) => { + const [a, b] = ratings; + const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400)); + const newRating = (rating, i) => + (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a)); + if (ratings.length === 2) return [newRating(a, 1), newRating(b, 0)]; + + for (let i = 0, len = ratings.length; i < len; i++) { + let j = i; + while (j < len - 1) { + j++; + [ratings[i], ratings[j]] = elo([ratings[i], ratings[j]], kFactor); + } + } + return ratings; +}; + const equals = (a, b) => { + if (a === b) return true; + if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime(); + if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b; + if (a === null || a === undefined || b === null || b === undefined) return false; + if (a.prototype !== b.prototype) return false; + let keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) return false; + return keys.every(k => equals(a[k], b[k])); +}; + const escapeHTML = str => + str.replace( + /[&<>'"]/g, + tag => + ({ + '&': '&', + '<': '<', + '>': '>', + "'": ''', + '"': '"' + }[tag] || tag) + ); + const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); + const extendHex = shortHex => + '#' + + shortHex + .slice(shortHex.startsWith('#') ? 1 : 0) + .split('') + .map(x => x + x) + .join(''); + const factorial = n => + n < 0 + ? (() => { + throw new TypeError('Negative numbers are not allowed!'); + })() + : n <= 1 + ? 1 + : n * factorial(n - 1); + const fibonacci = n => + Array.from({ length: n }).reduce( + (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), + [] + ); + const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); + const filterNonUniqueBy = (arr, fn) => + arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j))); + const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj)); + const findLast = (arr, fn) => arr.filter(fn).pop(); + const findLastIndex = (arr, fn) => + arr + .map((val, i) => [i, val]) + .filter(([i, val]) => fn(val, i, arr)) + .pop()[0]; + const findLastKey = (obj, fn) => + Object.keys(obj) + .reverse() + .find(key => fn(obj[key], key, obj)); + const flatten = (arr, depth = 1) => + arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []); + const flattenObject = (obj, prefix = '') => + Object.keys(obj).reduce((acc, k) => { + const pre = prefix.length ? prefix + '.' : ''; + if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k)); + else acc[pre + k] = obj[k]; + return acc; + }, {}); const flip = fn => (first, ...rest) => fn(...rest, first); - -const forEachRight = (arr, callback) => - arr - .slice(0) - .reverse() - .forEach(callback); - -const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj)); - -const forOwnRight = (obj, fn) => - Object.keys(obj) - .reverse() - .forEach(key => fn(obj[key], key, obj)); - -const formatDuration = ms => { - if (ms < 0) ms = -ms; - const time = { - day: Math.floor(ms / 86400000), - hour: Math.floor(ms / 3600000) % 24, - minute: Math.floor(ms / 60000) % 60, - second: Math.floor(ms / 1000) % 60, - millisecond: Math.floor(ms) % 1000 - }; - return Object.entries(time) - .filter(val => val[1] !== 0) - .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`) - .join(', '); -}; - -const fromCamelCase = (str, separator = '_') => - str - .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') - .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2') - .toLowerCase(); - -const functionName = fn => (console.debug(fn.name), fn); - -const functions = (obj, inherited = false) => - (inherited - ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))] - : Object.keys(obj) - ).filter(key => typeof obj[key] === 'function'); - -const gcd = (...arr) => { - const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); - return [...arr].reduce((a, b) => _gcd(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 get = (from, ...selectors) => - [...selectors].map(s => - s - .replace(/\[([^\[\]]*)\]/g, '.$1.') - .split('.') - .filter(t => t !== '') - .reduce((prev, cur) => prev && prev[cur], from) - ); - -const getColonTimeFromDate = date => date.toTimeString().slice(0, 8); - -const getDaysDiffBetweenDates = (dateInitial, dateFinal) => - (dateFinal - dateInitial) / (1000 * 3600 * 24); - -const getImages = (el, includeDuplicates = false) => { - const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src')); - return includeDuplicates ? images : [...new Set(images)]; -}; - -const getMeridiemSuffixOfInteger = num => - num === 0 || num === 24 - ? 12 + 'am' - : num === 12 - ? 12 + 'pm' - : num < 12 - ? (num % 12) + 'am' - : (num % 12) + 'pm'; - -const getScrollPosition = (el = window) => ({ - x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, - y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop -}); - -const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]; - -const getType = v => - v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase(); - -const getURLParameters = url => - (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( - (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), - {} - ); - -const groupBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { - acc[val] = (acc[val] || []).concat(arr[i]); - return acc; - }, {}); - -const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length; - -const hasClass = (el, className) => el.classList.contains(className); - -const hasFlags = (...flags) => - flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag)); - -const hashBrowser = val => - crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => { - let hexes = [], - view = new DataView(h); - for (let i = 0; i < view.byteLength; i += 4) - hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8)); - return hexes.join(''); - }); - -const crypto$2 = typeof require !== "undefined" && require('crypto'); -const hashNode = val => - new Promise(resolve => - setTimeout( - () => - resolve( - crypto$2 - .createHash('sha256') - .update(val) - .digest('hex') - ), - 0 - ) - ); - -const head = arr => arr[0]; - -const hexToRGB = hex => { - let alpha = false, - h = hex.slice(hex.startsWith('#') ? 1 : 0); - if (h.length === 3) h = [...h].map(x => x + x).join(''); - else if (h.length === 8) alpha = true; - h = parseInt(h, 16); - return ( - 'rgb' + - (alpha ? 'a' : '') + - '(' + - (h >>> (alpha ? 24 : 16)) + - ', ' + - ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) + - ', ' + - ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) + - (alpha ? `, ${h & 0x000000ff}` : '') + - ')' - ); -}; - -const hide = els => els.forEach(e => (e.style.display = 'none')); - -const httpGet = (url, callback, err = console.error) => { - const request = new XMLHttpRequest(); - request.open('GET', url, true); - request.onload = () => callback(request.responseText); - request.onerror = () => err(request); - request.send(); -}; - -const httpPost = (url, data, callback, err = console.error) => { - const request = new XMLHttpRequest(); - request.open('POST', url, true); - request.setRequestHeader('Content-type', 'application/json; charset=utf-8'); - request.onload = () => callback(request.responseText); - request.onerror = () => err(request); - request.send(data); -}; - -const httpsRedirect = () => { - if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); -}; - -const hz = (fn, iterations = 100) => { - const before = performance.now(); - for (let i = 0; i < iterations; i++) fn(); - return (1000 * iterations) / (performance.now() - before); -}; - -const inRange = (n, start, end = null) => { - if (end && start > end) [end, start] = [start, end]; - return end == null ? n >= 0 && n < start : n >= start && n < end; -}; - -const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count)); - -const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []); - -const initial = arr => arr.slice(0, -1); - -const initialize2DArray = (w, h, val = null) => - Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val)); - -const initializeArrayWithRange = (end, start = 0, step = 1) => - Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) => i * step + start); - -const initializeArrayWithRangeRight = (end, start = 0, step = 1) => - Array.from({ length: Math.ceil((end + 1 - start) / step) }).map( - (v, i, arr) => (arr.length - i - 1) * step + start - ); - -const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); - -const initializeNDArray = (val, ...args) => - args.length === 0 - ? val - : Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1))); - -const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString); - -const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString); - -const intersection = (a, b) => { - const s = new Set(b); - return a.filter(x => s.has(x)); -}; - -const intersectionBy = (a, b, fn) => { - const s = new Set(b.map(fn)); - return a.filter(x => s.has(fn(x))); -}; - -const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1); - -const invertKeyValues = (obj, fn) => - Object.keys(obj).reduce((acc, key) => { - const val = fn ? fn(obj[key]) : obj[key]; - acc[val] = acc[val] || []; - acc[val].push(key); - return acc; - }, {}); - -const is = (type, val) => ![, null].includes(val) && val.constructor === type; - -const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); - -const isAfterDate = (dateA, dateB) => dateA > dateB; - -const isAnagram = (str1, str2) => { - const normalize = str => - str - .toLowerCase() - .replace(/[^a-z0-9]/gi, '') - .split('') - .sort() - .join(''); - return normalize(str1) === normalize(str2); -}; - -const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function'; - -const isBeforeDate = (dateA, dateB) => dateA < dateB; - -const isBoolean = val => typeof val === 'boolean'; - -const isBrowser = () => ![typeof window, typeof document].includes('undefined'); - -const isBrowserTabFocused = () => !document.hidden; - -const isDivisible = (dividend, divisor) => dividend % divisor === 0; - -const isDuplexStream = val => - val !== null && - typeof val === 'object' && - typeof val.pipe === 'function' && - typeof val._read === 'function' && - typeof val._readableState === 'object' && - typeof val._write === 'function' && - typeof val._writableState === 'object'; - -const isEmpty = val => val == null || !(Object.keys(val) || val).length; - -const isEven = num => num % 2 === 0; - -const isFunction = val => typeof val === 'function'; - -const isLowerCase = str => str === str.toLowerCase(); - -const isNil = val => val === undefined || val === null; - -const isNull = val => val === null; - -const isNumber = val => typeof val === 'number'; - -const isObject = obj => obj === Object(obj); - -const isObjectLike = val => val !== null && typeof val === 'object'; - -const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object; - -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 isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null; - -const isPromiseLike = obj => - obj !== null && - (typeof obj === 'object' || typeof obj === 'function') && - typeof obj.then === 'function'; - -const isReadableStream = val => - val !== null && - typeof val === 'object' && - typeof val.pipe === 'function' && - typeof val._read === 'function' && - typeof val._readableState === 'object'; - -const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString(); - -const isSorted = arr => { - let direction = -(arr[0] - arr[1]); - for (let [i, val] of arr.entries()) { - direction = !direction ? -(arr[i - 1] - arr[i]) : direction; - if (i === arr.length - 1) return !direction ? 0 : direction; - else if ((val - arr[i + 1]) * direction > 0) return 0; - } -}; - -const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function'; - -const isString = val => typeof val === 'string'; - -const isSymbol = val => typeof val === 'symbol'; - -const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; - -const isUndefined = val => val === undefined; - -const isUpperCase = str => str === str.toUpperCase(); - -const isValidJSON = obj => { - try { - JSON.parse(obj); - return true; - } catch (e) { - return false; - } -}; - -const isWritableStream = val => - val !== null && - typeof val === 'object' && - typeof val.pipe === 'function' && - typeof val._write === 'function' && - typeof val._writableState === 'object'; - -const join = (arr, separator = ',', end = separator) => - arr.reduce( - (acc, val, i) => - i === arr.length - 2 - ? acc + val + end - : i === arr.length - 1 - ? acc + val - : acc + val + separator, - '' - ); - -const last = arr => arr[arr.length - 1]; - -const lcm = (...arr) => { - const gcd = (x, y) => (!y ? x : gcd(y, x % y)); - const _lcm = (x, y) => (x * y) / gcd(x, y); - return [...arr].reduce((a, b) => _lcm(a, b)); -}; - -const longestItem = (val, ...vals) => - [val, ...vals].reduce((a, x) => (x.length > a.length ? x : a)); - -const lowercaseKeys = obj => - Object.keys(obj).reduce((acc, key) => { - acc[key.toLowerCase()] = obj[key]; - return acc; - }, {}); - -const luhnCheck = num => { - let arr = (num + '') - .split('') - .reverse() - .map(x => parseInt(x)); - let lastDigit = arr.splice(0, 1)[0]; - let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9), 0); - sum += lastDigit; - return sum % 10 === 0; -}; - -const mapKeys = (obj, fn) => - Object.keys(obj).reduce((acc, k) => { - acc[fn(obj[k], k, obj)] = obj[k]; - return acc; - }, {}); - -const mapObject = (arr, fn) => - (a => ( - (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) - ))(); - -const mapString = (str, fn) => - str - .split('') - .map((c, i) => fn(c, i, str)) - .join(''); - -const mapValues = (obj, fn) => - Object.keys(obj).reduce((acc, k) => { - acc[k] = fn(obj[k], k, obj); - return acc; - }, {}); - -const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask); - -const matches = (obj, source) => - Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]); - -const matchesWith = (obj, source, fn) => - Object.keys(source).every( - key => - obj.hasOwnProperty(key) && fn - ? fn(obj[key], source[key], key, obj, source) - : obj[key] == source[key] - ); - -const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); - -const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates)); - -const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); - -const median = arr => { - const mid = Math.floor(arr.length / 2), - nums = [...arr].sort((a, b) => a - b); - return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; -}; - -const memoize = fn => { - const cache = new Map(); - const cached = function(val) { - return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val); - }; - cached.cache = cache; - return cached; -}; - -const merge = (...objs) => - [...objs].reduce( - (acc, obj) => - Object.keys(obj).reduce((a, k) => { - acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k]; - return acc; - }, {}), - {} - ); - -const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); - -const minDate = (...dates) => new Date(Math.min.apply(null, ...dates)); - -const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); - -const mostPerformant = (fns, iterations = 10000) => { - const times = fns.map(fn => { - const before = performance.now(); - for (let i = 0; i < iterations; i++) fn(); - return performance.now() - before; - }); - return times.indexOf(Math.min(...times)); -}; - -const negate = func => (...args) => !func(...args); - -const nest = (items, id = null, link = 'parent_id') => - items - .filter(item => item[link] === id) - .map(item => ({ ...item, children: nest(items, item.id) })); - -const nodeListToArray = nodeList => [...nodeList]; - -const none = (arr, fn = Boolean) => !arr.some(fn); - -const nthArg = n => (...args) => args.slice(n)[0]; - -const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0]; - -const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {}); - -const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); - -const observeMutations = (element, callback, options) => { - const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m))); - observer.observe( - element, - Object.assign( - { - childList: true, - attributes: true, - attributeOldValue: true, - characterData: true, - characterDataOldValue: true, - subtree: true - }, - options - ) - ); - return observer; -}; - -const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); - -const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)]; - -const omit = (obj, arr) => - Object.keys(obj) - .filter(k => !arr.includes(k)) - .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); - -const omitBy = (obj, fn) => - Object.keys(obj) - .filter(k => !fn(obj[k], k)) - .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); - -const on = (el, evt, fn, opts = {}) => { - const delegatorFn = e => e.target.matches(opts.target) && fn.call(e.target, e); - el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false); - if (opts.target) return delegatorFn; -}; - -const onUserInputChange = callback => { - let type = 'mouse', - lastTime = 0; - const mousemoveHandler = () => { - const now = performance.now(); - if (now - lastTime < 20) - (type = 'mouse'), callback(type), document.removeEventListener('mousemove', mousemoveHandler); - lastTime = now; - }; - document.addEventListener('touchstart', () => { - if (type === 'touch') return; - (type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler); - }); -}; - -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) => { - if (acc === 0) { - const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]]; - acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0; - } - return acc; - }, 0) - ); - -const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); - -const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val))); - -const pad = (str, length, char = ' ') => - str.padStart((str.length + length) / 2, char).padEnd(length, char); - -const palindrome = str => { - const s = str.toLowerCase().replace(/[\W_]/g, ''); - return s === [...s].reverse().join(''); -}; - -const parseCookie = str => - str - .split(';') - .map(v => v.split('=')) - .reduce((acc, v) => { - acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim()); - return acc; - }, {}); - -const partial = (fn, ...partials) => (...args) => fn(...partials, ...args); - -const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials); - -const partition = (arr, fn) => - arr.reduce( - (acc, val, i, arr) => { - acc[fn(val, i, arr) ? 0 : 1].push(val); - return acc; - }, - [[], []] - ); - -const percentile = (arr, val) => - (100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0)) / arr.length; - -const permutations = arr => { - if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr; - return arr.reduce( - (acc, item, i) => - acc.concat( - permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val]) - ), - [] - ); -}; - -const pick = (obj, arr) => - arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); - -const pickBy = (obj, fn) => - Object.keys(obj) - .filter(k => fn(obj[k], k)) - .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); - -const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); - -const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); - -const pluralize = (val, word, plural = word + 's') => { - const _pluralize = (num, word, plural = word + 's') => - [1, -1].includes(Number(num)) ? word : plural; - if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]); - return _pluralize(val, word, plural); -}; - -const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); - -const prefix = prop => { - const capitalizedProp = prop.charAt(0).toUpperCase() + prop.slice(1); - const prefixes = ['', 'webkit', 'moz', 'ms', 'o']; - const i = prefixes.findIndex( - prefix => typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !== 'undefined' - ); - return i !== -1 ? (i === 0 ? prop : prefixes[i] + capitalizedProp) : null; -}; - -const prettyBytes = (num, precision = 3, addSpace = true) => { - const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0]; - const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1); - const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision)); - return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent]; -}; - -const primes = num => { - let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2), - sqroot = Math.floor(Math.sqrt(num)), - numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2); - numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x))); - return arr; -}; - -const promisify = func => (...args) => - new Promise((resolve, reject) => - func(...args, (err, result) => (err ? reject(err) : resolve(result))) - ); - -const pull = (arr, ...args) => { - let argState = Array.isArray(args[0]) ? args[0] : args; - let pulled = arr.filter((v, i) => !argState.includes(v)); - arr.length = 0; - pulled.forEach(v => arr.push(v)); -}; - -const pullAtIndex = (arr, pullArr) => { - let removed = []; - let pulled = arr - .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v)) - .filter((v, i) => !pullArr.includes(i)); - arr.length = 0; - pulled.forEach(v => arr.push(v)); - return removed; -}; - -const pullAtValue = (arr, pullArr) => { - let removed = [], - pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)), - mutateTo = arr.filter((v, i) => !pullArr.includes(v)); - arr.length = 0; - mutateTo.forEach(v => arr.push(v)); - return removed; -}; - -const pullBy = (arr, ...args) => { - const length = args.length; - let fn = length > 1 ? args[length - 1] : undefined; - fn = typeof fn == 'function' ? (args.pop(), fn) : undefined; - let argState = (Array.isArray(args[0]) ? args[0] : args).map(val => fn(val)); - let pulled = arr.filter((v, i) => !argState.includes(fn(v))); - arr.length = 0; - pulled.forEach(v => arr.push(v)); -}; - -const radsToDegrees = rad => (rad * 180.0) / Math.PI; - -const randomHexColorCode = () => { - let n = (Math.random() * 0xfffff * 1000000).toString(16); - return '#' + n.slice(0, 6); -}; - -const randomIntArrayInRange = (min, max, n = 1) => - Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); - -const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; - -const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; - -const fs$1 = typeof require !== "undefined" && require('fs'); -const readFileLines = filename => - fs$1 - .readFileSync(filename) - .toString('UTF8') - .split('\n'); - -const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i])); - -const recordAnimationFrames = (callback, autoStart = true) => { - let running = true, - raf; - const stop = () => { - running = false; - cancelAnimationFrame(raf); - }; - const start = () => { - running = true; - run(); - }; - const run = () => { - raf = requestAnimationFrame(() => { - callback(); - if (running) run(); - }); - }; - if (autoStart) start(); - return { start, stop }; -}; - -const redirect = (url, asLink = true) => - asLink ? (window.location.href = url) : window.location.replace(url); - -const reduceSuccessive = (arr, fn, acc) => - arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]); - -const reduceWhich = (arr, comparator = (a, b) => a - b) => - arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a)); - -const reducedFilter = (data, keys, fn) => - data.filter(fn).map(el => - keys.reduce((acc, key) => { - acc[key] = el[key]; - return acc; - }, {}) - ); - -const reject = (pred, array) => array.filter((...args) => !pred(...args)); - -const remove = (arr, func) => - Array.isArray(arr) - ? arr.filter(func).reduce((acc, val) => { - arr.splice(arr.indexOf(val), 1); - return acc.concat(val); - }, []) - : []; - -const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); - -const renameKeys = (keysMap, obj) => - Object.keys(obj).reduce( - (acc, key) => ({ - ...acc, - ...{ [keysMap[key] || key]: obj[key] } - }), - {} - ); - -const reverseString = str => [...str].reverse().join(''); - -const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); - -const runAsync = fn => { - const worker = new Worker( - URL.createObjectURL(new Blob([`postMessage((${fn})());`]), { - type: 'application/javascript; charset=utf-8' - }) - ); - return new Promise((res, rej) => { - worker.onmessage = ({ data }) => { - res(data), worker.terminate(); - }; - worker.onerror = err => { - rej(err), worker.terminate(); - }; - }); -}; - -const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); - -const sample = arr => arr[Math.floor(Math.random() * arr.length)]; - -const sampleSize = ([...arr], n = 1) => { - let m = arr.length; - while (m) { - const i = Math.floor(Math.random() * m--); - [arr[m], arr[i]] = [arr[i], arr[m]]; - } - return arr.slice(0, n); -}; - -const scrollToTop = () => { - const c = document.documentElement.scrollTop || document.body.scrollTop; - if (c > 0) { - window.requestAnimationFrame(scrollToTop); - window.scrollTo(0, c - c / 8); - } -}; - -const sdbm = str => { - let arr = str.split(''); - return arr.reduce( - (hashCode, currentVal) => - (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode), - 0 - ); -}; - -const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; - -const setStyle = (el, ruleName, val) => (el.style[ruleName] = val); - -const shallowClone = obj => Object.assign({}, obj); - -const shank = (arr, index = 0, delCount = 0, ...elements) => - arr - .slice(0, index) - .concat(elements) - .concat(arr.slice(index + delCount)); - -const show = (...el) => [...el].forEach(e => (e.style.display = '')); - -const shuffle = ([...arr]) => { - let m = arr.length; - while (m) { - const i = Math.floor(Math.random() * m--); - [arr[m], arr[i]] = [arr[i], arr[m]]; - } - return arr; -}; - -const similarity = (arr, values) => arr.filter(v => values.includes(v)); - -const size = val => - Array.isArray(val) - ? val.length - : val && typeof val === 'object' - ? val.size || val.length || Object.keys(val).length - : typeof val === 'string' - ? new Blob([val]).size - : 0; - -const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); - -const smoothScroll = element => - document.querySelector(element).scrollIntoView({ - behavior: 'smooth' - }); - -const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join(''); - -const sortedIndex = (arr, n) => { - const isDescending = arr[0] > arr[arr.length - 1]; - const index = arr.findIndex(el => (isDescending ? n >= el : n <= el)); - return index === -1 ? arr.length : index; -}; - -const sortedIndexBy = (arr, n, fn) => { - const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); - const val = fn(n); - const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el))); - return index === -1 ? arr.length : index; -}; - -const sortedLastIndex = (arr, n) => { - const isDescending = arr[0] > arr[arr.length - 1]; - const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el)); - return index === -1 ? 0 : arr.length - index; -}; - -const sortedLastIndexBy = (arr, n, fn) => { - const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); - const val = fn(n); - const index = arr - .map(fn) - .reverse() - .findIndex(el => (isDescending ? val <= el : val >= el)); - return index === -1 ? 0 : arr.length - index; -}; - -const splitLines = str => str.split(/\r?\n/); - + const forEachRight = (arr, callback) => + arr + .slice(0) + .reverse() + .forEach(callback); + const formatDuration = ms => { + if (ms < 0) ms = -ms; + const time = { + day: Math.floor(ms / 86400000), + hour: Math.floor(ms / 3600000) % 24, + minute: Math.floor(ms / 60000) % 60, + second: Math.floor(ms / 1000) % 60, + millisecond: Math.floor(ms) % 1000 + }; + return Object.entries(time) + .filter(val => val[1] !== 0) + .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`) + .join(', '); +}; + const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj)); + const forOwnRight = (obj, fn) => + Object.keys(obj) + .reverse() + .forEach(key => fn(obj[key], key, obj)); + const fromCamelCase = (str, separator = '_') => + str + .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') + .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2') + .toLowerCase(); + const functionName = fn => (console.debug(fn.name), fn); + const functions = (obj, inherited = false) => + (inherited + ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))] + : Object.keys(obj) + ).filter(key => typeof obj[key] === 'function'); + const gcd = (...arr) => { + const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); + return [...arr].reduce((a, b) => _gcd(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 get = (from, ...selectors) => + [...selectors].map(s => + s + .replace(/\[([^\[\]]*)\]/g, '.$1.') + .split('.') + .filter(t => t !== '') + .reduce((prev, cur) => prev && prev[cur], from) + ); + const getColonTimeFromDate = date => date.toTimeString().slice(0, 8); + const getDaysDiffBetweenDates = (dateInitial, dateFinal) => + (dateFinal - dateInitial) / (1000 * 3600 * 24); + const getImages = (el, includeDuplicates = false) => { + const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src')); + return includeDuplicates ? images : [...new Set(images)]; +}; + const getMeridiemSuffixOfInteger = num => + num === 0 || num === 24 + ? 12 + 'am' + : num === 12 + ? 12 + 'pm' + : num < 12 + ? (num % 12) + 'am' + : (num % 12) + 'pm'; + const getScrollPosition = (el = window) => ({ + x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, + y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop +}); + const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]; + const getType = v => + v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase(); + const getURLParameters = url => + (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( + (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), + {} + ); + const groupBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { + acc[val] = (acc[val] || []).concat(arr[i]); + return acc; + }, {}); + const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length; + const hasClass = (el, className) => el.classList.contains(className); + const hasFlags = (...flags) => + flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag)); + const hashBrowser = val => + crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => { + let hexes = [], + view = new DataView(h); + for (let i = 0; i < view.byteLength; i += 4) + hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8)); + return hexes.join(''); + }); + +const hashNode = val => + new Promise(resolve => + setTimeout( + () => + resolve( + crypto + .createHash('sha256') + .update(val) + .digest('hex') + ), + 0 + ) + ); + const head = arr => arr[0]; + const hexToRGB = hex => { + let alpha = false, + h = hex.slice(hex.startsWith('#') ? 1 : 0); + if (h.length === 3) h = [...h].map(x => x + x).join(''); + else if (h.length === 8) alpha = true; + h = parseInt(h, 16); + return ( + 'rgb' + + (alpha ? 'a' : '') + + '(' + + (h >>> (alpha ? 24 : 16)) + + ', ' + + ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) + + ', ' + + ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) + + (alpha ? `, ${h & 0x000000ff}` : '') + + ')' + ); +}; + const hide = els => els.forEach(e => (e.style.display = 'none')); + const httpGet = (url, callback, err = console.error) => { + const request = new XMLHttpRequest(); + request.open('GET', url, true); + request.onload = () => callback(request.responseText); + request.onerror = () => err(request); + request.send(); +}; + const httpPost = (url, data, callback, err = console.error) => { + const request = new XMLHttpRequest(); + request.open('POST', url, true); + request.setRequestHeader('Content-type', 'application/json; charset=utf-8'); + request.onload = () => callback(request.responseText); + request.onerror = () => err(request); + request.send(data); +}; + const httpsRedirect = () => { + if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); +}; + const hz = (fn, iterations = 100) => { + const before = performance.now(); + for (let i = 0; i < iterations; i++) fn(); + return (1000 * iterations) / (performance.now() - before); +}; + const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count)); + const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []); + const initial = arr => arr.slice(0, -1); + const initialize2DArray = (w, h, val = null) => + Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val)); + const initializeArrayWithRange = (end, start = 0, step = 1) => + Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) => i * step + start); + const initializeArrayWithRangeRight = (end, start = 0, step = 1) => + Array.from({ length: Math.ceil((end + 1 - start) / step) }).map( + (v, i, arr) => (arr.length - i - 1) * step + start + ); + const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); + const initializeNDArray = (val, ...args) => + args.length === 0 + ? val + : Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1))); + const inRange = (n, start, end = null) => { + if (end && start > end) [end, start] = [start, end]; + return end == null ? n >= 0 && n < start : n >= start && n < end; +}; + const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString); + const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString); + const intersection = (a, b) => { + const s = new Set(b); + return a.filter(x => s.has(x)); +}; + const intersectionBy = (a, b, fn) => { + const s = new Set(b.map(fn)); + return a.filter(x => s.has(fn(x))); +}; + const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1); + const invertKeyValues = (obj, fn) => + Object.keys(obj).reduce((acc, key) => { + const val = fn ? fn(obj[key]) : obj[key]; + acc[val] = acc[val] || []; + acc[val].push(key); + return acc; + }, {}); + const is = (type, val) => ![, null].includes(val) && val.constructor === type; + const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); + const isAfterDate = (dateA, dateB) => dateA > dateB; + const isAnagram = (str1, str2) => { + const normalize = str => + str + .toLowerCase() + .replace(/[^a-z0-9]/gi, '') + .split('') + .sort() + .join(''); + return normalize(str1) === normalize(str2); +}; + const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function'; + const isBeforeDate = (dateA, dateB) => dateA < dateB; + const isBoolean = val => typeof val === 'boolean'; + const isBrowser = () => ![typeof window, typeof document].includes('undefined'); + const isBrowserTabFocused = () => !document.hidden; + const isDivisible = (dividend, divisor) => dividend % divisor === 0; + const isDuplexStream = val => + val !== null && + typeof val === 'object' && + typeof val.pipe === 'function' && + typeof val._read === 'function' && + typeof val._readableState === 'object' && + typeof val._write === 'function' && + typeof val._writableState === 'object'; + const isEmpty = val => val == null || !(Object.keys(val) || val).length; + const isEven = num => num % 2 === 0; + const isFunction = val => typeof val === 'function'; + const isLowerCase = str => str === str.toLowerCase(); + const isNil = val => val === undefined || val === null; + const isNull = val => val === null; + const isNumber = val => typeof val === 'number'; + const isObject = obj => obj === Object(obj); + const isObjectLike = val => val !== null && typeof val === 'object'; + const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object; + 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 isPrimitive = val => Object(val) !== val; + const isPromiseLike = obj => + obj !== null && + (typeof obj === 'object' || typeof obj === 'function') && + typeof obj.then === 'function'; + const isReadableStream = val => + val !== null && + typeof val === 'object' && + typeof val.pipe === 'function' && + typeof val._read === 'function' && + typeof val._readableState === 'object'; + const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString(); + const isSorted = arr => { + let direction = -(arr[0] - arr[1]); + for (let [i, val] of arr.entries()) { + direction = !direction ? -(arr[i - 1] - arr[i]) : direction; + if (i === arr.length - 1) return !direction ? 0 : direction; + else if ((val - arr[i + 1]) * direction > 0) return 0; + } +}; + const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function'; + const isString = val => typeof val === 'string'; + const isSymbol = val => typeof val === 'symbol'; + const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; + const isUndefined = val => val === undefined; + const isUpperCase = str => str === str.toUpperCase(); + const isValidJSON = obj => { + try { + JSON.parse(obj); + return true; + } catch (e) { + return false; + } +}; + const isWritableStream = val => + val !== null && + typeof val === 'object' && + typeof val.pipe === 'function' && + typeof val._write === 'function' && + typeof val._writableState === 'object'; + const join = (arr, separator = ',', end = separator) => + arr.reduce( + (acc, val, i) => + i === arr.length - 2 + ? acc + val + end + : i === arr.length - 1 + ? acc + val + : acc + val + separator, + '' + ); + const JSONtoCSV = (arr, columns, delimiter = ',') => + [ + columns.join(delimiter), + ...arr.map(obj => + columns.reduce( + (acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`, + '' + ) + ) + ].join('\n'); + +const JSONToFile = (obj, filename) => + fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); + const last = arr => arr[arr.length - 1]; + const lcm = (...arr) => { + const gcd = (x, y) => (!y ? x : gcd(y, x % y)); + const _lcm = (x, y) => (x * y) / gcd(x, y); + return [...arr].reduce((a, b) => _lcm(a, b)); +}; + const longestItem = (val, ...vals) => + [val, ...vals].reduce((a, x) => (x.length > a.length ? x : a)); + const lowercaseKeys = obj => + Object.keys(obj).reduce((acc, key) => { + acc[key.toLowerCase()] = obj[key]; + return acc; + }, {}); + const luhnCheck = num => { + let arr = (num + '') + .split('') + .reverse() + .map(x => parseInt(x)); + let lastDigit = arr.splice(0, 1)[0]; + let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9), 0); + sum += lastDigit; + return sum % 10 === 0; +}; + const mapKeys = (obj, fn) => + Object.keys(obj).reduce((acc, k) => { + acc[fn(obj[k], k, obj)] = obj[k]; + return acc; + }, {}); + const mapObject = (arr, fn) => + (a => ( + (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) + ))(); + const mapString = (str, fn) => + str + .split('') + .map((c, i) => fn(c, i, str)) + .join(''); + const mapValues = (obj, fn) => + Object.keys(obj).reduce((acc, k) => { + acc[k] = fn(obj[k], k, obj); + return acc; + }, {}); + const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask); + const matches = (obj, source) => + Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]); + const matchesWith = (obj, source, fn) => + Object.keys(source).every( + key => + obj.hasOwnProperty(key) && fn + ? fn(obj[key], source[key], key, obj, source) + : obj[key] == source[key] + ); + const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); + const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates)); + const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); + const median = arr => { + const mid = Math.floor(arr.length / 2), + nums = [...arr].sort((a, b) => a - b); + return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; +}; + const memoize = fn => { + const cache = new Map(); + const cached = function(val) { + return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val); + }; + cached.cache = cache; + return cached; +}; + const merge = (...objs) => + [...objs].reduce( + (acc, obj) => + Object.keys(obj).reduce((a, k) => { + acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k]; + return acc; + }, {}), + {} + ); + const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); + const minDate = (...dates) => new Date(Math.min.apply(null, ...dates)); + const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); + const mostPerformant = (fns, iterations = 10000) => { + const times = fns.map(fn => { + const before = performance.now(); + for (let i = 0; i < iterations; i++) fn(); + return performance.now() - before; + }); + return times.indexOf(Math.min(...times)); +}; + const negate = func => (...args) => !func(...args); + const nest = (items, id = null, link = 'parent_id') => + items + .filter(item => item[link] === id) + .map(item => ({ ...item, children: nest(items, item.id) })); + const nodeListToArray = nodeList => [...nodeList]; + const none = (arr, fn = Boolean) => !arr.some(fn); + const nthArg = n => (...args) => args.slice(n)[0]; + const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0]; + const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {}); + const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); + const observeMutations = (element, callback, options) => { + const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m))); + observer.observe( + element, + Object.assign( + { + childList: true, + attributes: true, + attributeOldValue: true, + characterData: true, + characterDataOldValue: true, + subtree: true + }, + options + ) + ); + return observer; +}; + const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); + const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)]; + const omit = (obj, arr) => + Object.keys(obj) + .filter(k => !arr.includes(k)) + .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); + const omitBy = (obj, fn) => + Object.keys(obj) + .filter(k => !fn(obj[k], k)) + .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); + const on = (el, evt, fn, opts = {}) => { + const delegatorFn = e => e.target.matches(opts.target) && fn.call(e.target, e); + el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false); + if (opts.target) return delegatorFn; +}; + 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; + const mousemoveHandler = () => { + const now = performance.now(); + if (now - lastTime < 20) + (type = 'mouse'), callback(type), document.removeEventListener('mousemove', mousemoveHandler); + lastTime = now; + }; + document.addEventListener('touchstart', () => { + if (type === 'touch') return; + (type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler); + }); +}; + const orderBy = (arr, props, orders) => + [...arr].sort((a, b) => + props.reduce((acc, prop, i) => { + if (acc === 0) { + const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]]; + acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0; + } + return acc; + }, 0) + ); + const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); + const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val))); + const pad = (str, length, char = ' ') => + str.padStart((str.length + length) / 2, char).padEnd(length, char); + const palindrome = str => { + const s = str.toLowerCase().replace(/[\W_]/g, ''); + return s === [...s].reverse().join(''); +}; + const parseCookie = str => + str + .split(';') + .map(v => v.split('=')) + .reduce((acc, v) => { + acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim()); + return acc; + }, {}); + const partial = (fn, ...partials) => (...args) => fn(...partials, ...args); + const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials); + const partition = (arr, fn) => + arr.reduce( + (acc, val, i, arr) => { + acc[fn(val, i, arr) ? 0 : 1].push(val); + return acc; + }, + [[], []] + ); + const percentile = (arr, val) => + (100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0)) / arr.length; + const permutations = arr => { + if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr; + return arr.reduce( + (acc, item, i) => + acc.concat( + permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val]) + ), + [] + ); +}; + const pick = (obj, arr) => + arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); + const pickBy = (obj, fn) => + Object.keys(obj) + .filter(k => fn(obj[k], k)) + .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); + const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); + const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); + const pluralize = (val, word, plural = word + 's') => { + const _pluralize = (num, word, plural = word + 's') => + [1, -1].includes(Number(num)) ? word : plural; + if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]); + return _pluralize(val, word, plural); +}; + const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); + const prefix = prop => { + const capitalizedProp = prop.charAt(0).toUpperCase() + prop.slice(1); + const prefixes = ['', 'webkit', 'moz', 'ms', 'o']; + const i = prefixes.findIndex( + prefix => typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !== 'undefined' + ); + return i !== -1 ? (i === 0 ? prop : prefixes[i] + capitalizedProp) : null; +}; + const prettyBytes = (num, precision = 3, addSpace = true) => { + const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0]; + const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1); + const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision)); + return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent]; +}; + const primes = num => { + let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2), + sqroot = Math.floor(Math.sqrt(num)), + numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2); + numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x))); + return arr; +}; + const promisify = func => (...args) => + new Promise((resolve, reject) => + func(...args, (err, result) => (err ? reject(err) : resolve(result))) + ); + const pull = (arr, ...args) => { + let argState = Array.isArray(args[0]) ? args[0] : args; + let pulled = arr.filter((v, i) => !argState.includes(v)); + arr.length = 0; + pulled.forEach(v => arr.push(v)); +}; + const pullAtIndex = (arr, pullArr) => { + let removed = []; + let pulled = arr + .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v)) + .filter((v, i) => !pullArr.includes(i)); + arr.length = 0; + pulled.forEach(v => arr.push(v)); + return removed; +}; + const pullAtValue = (arr, pullArr) => { + let removed = [], + pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)), + mutateTo = arr.filter((v, i) => !pullArr.includes(v)); + arr.length = 0; + mutateTo.forEach(v => arr.push(v)); + return removed; +}; + const pullBy = (arr, ...args) => { + const length = args.length; + let fn = length > 1 ? args[length - 1] : undefined; + fn = typeof fn == 'function' ? (args.pop(), fn) : undefined; + let argState = (Array.isArray(args[0]) ? args[0] : args).map(val => fn(val)); + let pulled = arr.filter((v, i) => !argState.includes(fn(v))); + arr.length = 0; + pulled.forEach(v => arr.push(v)); +}; + const radsToDegrees = rad => (rad * 180.0) / Math.PI; + const randomHexColorCode = () => { + let n = (Math.random() * 0xfffff * 1000000).toString(16); + return '#' + n.slice(0, 6); +}; + const randomIntArrayInRange = (min, max, n = 1) => + Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); + const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; + const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; + +const readFileLines = filename => + fs + .readFileSync(filename) + .toString('UTF8') + .split('\n'); + const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i])); + const recordAnimationFrames = (callback, autoStart = true) => { + let running = true, + raf; + const stop = () => { + running = false; + cancelAnimationFrame(raf); + }; + const start = () => { + running = true; + run(); + }; + const run = () => { + raf = requestAnimationFrame(() => { + callback(); + if (running) run(); + }); + }; + if (autoStart) start(); + return { start, stop }; +}; + const redirect = (url, asLink = true) => + asLink ? (window.location.href = url) : window.location.replace(url); + const reducedFilter = (data, keys, fn) => + data.filter(fn).map(el => + keys.reduce((acc, key) => { + acc[key] = el[key]; + return acc; + }, {}) + ); + const reduceSuccessive = (arr, fn, acc) => + arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]); + const reduceWhich = (arr, comparator = (a, b) => a - b) => + arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a)); + const reject = (pred, array) => array.filter((...args) => !pred(...args)); + const remove = (arr, func) => + Array.isArray(arr) + ? arr.filter(func).reduce((acc, val) => { + arr.splice(arr.indexOf(val), 1); + return acc.concat(val); + }, []) + : []; + const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); + const renameKeys = (keysMap, obj) => + Object.keys(obj).reduce( + (acc, key) => ({ + ...acc, + ...{ [keysMap[key] || key]: obj[key] } + }), + {} + ); + const reverseString = str => [...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 => { + const worker = new Worker( + URL.createObjectURL(new Blob([`postMessage((${fn})());`]), { + type: 'application/javascript; charset=utf-8' + }) + ); + return new Promise((res, rej) => { + worker.onmessage = ({ data }) => { + res(data), worker.terminate(); + }; + worker.onerror = err => { + rej(err), worker.terminate(); + }; + }); +}; + const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); + const sample = arr => arr[Math.floor(Math.random() * arr.length)]; + const sampleSize = ([...arr], n = 1) => { + let m = arr.length; + while (m) { + const i = Math.floor(Math.random() * m--); + [arr[m], arr[i]] = [arr[i], arr[m]]; + } + return arr.slice(0, n); +}; + const scrollToTop = () => { + const c = document.documentElement.scrollTop || document.body.scrollTop; + if (c > 0) { + window.requestAnimationFrame(scrollToTop); + window.scrollTo(0, c - c / 8); + } +}; + const sdbm = str => { + let arr = str.split(''); + return arr.reduce( + (hashCode, currentVal) => + (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode), + 0 + ); +}; + const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; + const setStyle = (el, ruleName, val) => (el.style[ruleName] = val); + const shallowClone = obj => Object.assign({}, obj); + const shank = (arr, index = 0, delCount = 0, ...elements) => + arr + .slice(0, index) + .concat(elements) + .concat(arr.slice(index + delCount)); + const show = (...el) => [...el].forEach(e => (e.style.display = '')); + const shuffle = ([...arr]) => { + let m = arr.length; + while (m) { + const i = Math.floor(Math.random() * m--); + [arr[m], arr[i]] = [arr[i], arr[m]]; + } + return arr; +}; + const similarity = (arr, values) => arr.filter(v => values.includes(v)); + const size = val => + Array.isArray(val) + ? val.length + : val && typeof val === 'object' + ? val.size || val.length || Object.keys(val).length + : typeof val === 'string' + ? new Blob([val]).size + : 0; + const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + const smoothScroll = element => + document.querySelector(element).scrollIntoView({ + behavior: 'smooth' + }); + const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join(''); + const sortedIndex = (arr, n) => { + const isDescending = arr[0] > arr[arr.length - 1]; + const index = arr.findIndex(el => (isDescending ? n >= el : n <= el)); + return index === -1 ? arr.length : index; +}; + const sortedIndexBy = (arr, n, fn) => { + const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); + const val = fn(n); + const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el))); + return index === -1 ? arr.length : index; +}; + const sortedLastIndex = (arr, n) => { + const isDescending = arr[0] > arr[arr.length - 1]; + const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el)); + return index === -1 ? 0 : arr.length - index; +}; + const sortedLastIndexBy = (arr, n, fn) => { + const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); + const val = fn(n); + const index = arr + .map(fn) + .reverse() + .findIndex(el => (isDescending ? val <= el : val >= el)); + return index === -1 ? 0 : arr.length - index; +}; + const splitLines = str => str.split(/\r?\n/); const spreadOver = fn => argsArr => fn(...argsArr); + const stableSort = (arr, compare) => + arr + .map((item, index) => ({ item, index })) + .sort((a, b) => compare(a.item, b.item) || a.index - b.index) + .map(({ item }) => item); + const standardDeviation = (arr, usePopulation = false) => { + const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length; + return Math.sqrt( + arr.reduce((acc, val) => acc.concat((val - mean) ** 2), []).reduce((acc, val) => acc + val, 0) / + (arr.length - (usePopulation ? 0 : 1)) + ); +}; + const stringPermutations = str => { + if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; + return str + .split('') + .reduce( + (acc, letter, i) => + acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), + [] + ); +}; + const stripHTMLTags = str => str.replace(/<[^>]*>/g, ''); + const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); + const sumBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0); + const sumPower = (end, power = 2, start = 1) => + Array(end + 1 - start) + .fill(0) + .map((x, i) => (i + start) ** power) + .reduce((a, b) => a + b, 0); + const symmetricDifference = (a, b) => { + const sA = new Set(a), + sB = new Set(b); + return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; +}; + const symmetricDifferenceBy = (a, b, fn) => { + const sA = new Set(a.map(v => fn(v))), + sB = new Set(b.map(v => fn(v))); + return [...a.filter(x => !sB.has(fn(x))), ...b.filter(x => !sA.has(fn(x)))]; +}; + const symmetricDifferenceWith = (arr, val, comp) => [ + ...arr.filter(a => val.findIndex(b => comp(a, b)) === -1), + ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1) +]; + const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); + const take = (arr, n = 1) => arr.slice(0, n); + const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); + const takeRightWhile = (arr, func) => + arr.reduceRight((acc, el) => (func(el) ? acc : [el, ...acc]), []); + const takeWhile = (arr, func) => { + for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i); + return arr; +}; + const throttle = (fn, wait) => { + let inThrottle, lastFn, lastTime; + return function() { + const context = this, + args = arguments; + if (!inThrottle) { + fn.apply(context, args); + lastTime = Date.now(); + inThrottle = true; + } else { + clearTimeout(lastFn); + lastFn = setTimeout(function() { + if (Date.now() - lastTime >= wait) { + fn.apply(context, args); + lastTime = Date.now(); + } + }, Math.max(wait - (Date.now() - lastTime), 0)); + } + }; +}; + const times = (n, fn, context = undefined) => { + let i = 0; + while (fn.call(context, i) !== false && ++i < n) {} +}; + const timeTaken = callback => { + console.time('timeTaken'); + const r = callback(); + console.timeEnd('timeTaken'); + return r; +}; + const toCamelCase = str => { + let s = + 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(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase()) + .join(''); + return s.slice(0, 1).toLowerCase() + s.slice(1); +}; + const toCurrency = (n, curr, LanguageFormat = undefined) => + Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n); + const toDecimalMark = num => num.toLocaleString('en-US'); + const toggleClass = (el, className) => el.classList.toggle(className); + const toHash = (object, key) => + Array.prototype.reduce.call( + object, + (acc, data, index) => ((acc[!key ? index : data[key]] = data), acc), + {} + ); + const toKebabCase = str => + 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(x => x.toLowerCase()) + .join('-'); + const tomorrow = (long = false) => { + let t = new Date(); + t.setDate(t.getDate() + 1); + const ret = `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String( + t.getDate() + ).padStart(2, '0')}`; + return !long ? ret : `${ret}T00:00:00`; +}; + const toOrdinalSuffix = num => { + const int = parseInt(num), + digits = [int % 10, int % 100], + ordinals = ['st', 'nd', 'rd', 'th'], + oPattern = [1, 2, 3, 4], + tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19]; + return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) + ? int + ordinals[digits[0] - 1] + : int + ordinals[3]; +}; + const toSafeInteger = num => + Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)); + const toSnakeCase = str => + 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(x => x.toLowerCase()) + .join('_'); + const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc); + const triggerEvent = (el, eventType, detail) => + el.dispatchEvent(new CustomEvent(eventType, { detail })); + const truncateString = (str, num) => + str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; + const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]); + const unary = fn => val => fn(val); + const uncurry = (fn, n = 1) => (...args) => { + const next = acc => args => args.reduce((x, y) => x(y), acc); + if (n > args.length) throw new RangeError('Arguments too few!'); + return next(fn)(args.slice(0, n)); +}; + const unescapeHTML = str => + str.replace( + /&|<|>|'|"/g, + tag => + ({ + '&': '&', + '<': '<', + '>': '>', + ''': "'", + '"': '"' + }[tag] || tag) + ); + const unflattenObject = obj => + Object.keys(obj).reduce((acc, k) => { + if (k.indexOf('.') !== -1) { + const keys = k.split('.'); + Object.assign( + acc, + JSON.parse( + '{' + + keys.map((v, i) => (i !== keys.length - 1 ? `"${v}":{` : `"${v}":`)).join('') + + obj[k] + + '}'.repeat(keys.length) + ) + ); + } else acc[k] = obj[k]; + return acc; + }, {}); + const unfold = (fn, seed) => { + let result = [], + val = [null, seed]; + while ((val = fn(val[1]))) result.push(val[0]); + return result; +}; + const union = (a, b) => Array.from(new Set([...a, ...b])); + const unionBy = (a, b, fn) => { + const s = new Set(a.map(fn)); + return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))])); +}; + const unionWith = (a, b, comp) => + Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)])); + const uniqueElements = arr => [...new Set(arr)]; + const uniqueElementsBy = (arr, fn) => + arr.reduce((acc, v) => { + if (!acc.some(x => fn(v, x))) acc.push(v); + return acc; + }, []); + const uniqueElementsByRight = (arr, fn) => + arr.reduceRight((acc, v) => { + if (!acc.some(x => fn(v, x))) acc.push(v); + return acc; + }, []); + const uniqueSymmetricDifference = (a, b) => [ + ...new Set([...a.filter(v => !b.includes(v)), ...b.filter(v => !a.includes(v))]) +]; + const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`); + const unzip = arr => + arr.reduce( + (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), + Array.from({ + length: Math.max(...arr.map(x => x.length)) + }).map(x => []) + ); + const unzipWith = (arr, fn) => + arr + .reduce( + (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), + Array.from({ + length: Math.max(...arr.map(x => x.length)) + }).map(x => []) + ) + .map(val => fn(...val)); + const URLJoin = (...args) => + args + .join('/') + .replace(/[\/]+/g, '/') + .replace(/^(.+):\//, '$1://') + .replace(/^file:/, 'file:/') + .replace(/\/(\?|&|#[^!])/g, '$1') + .replace(/\?/g, '&') + .replace('&', '?'); + const UUIDGeneratorBrowser = () => + ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => + (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16) + ); + +const UUIDGeneratorNode = () => + ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => + (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16) + ); + const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; + const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x); + const without = (arr, ...args) => arr.filter(v => !args.includes(v)); + const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); + const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []); + const yesNo = (val, def = false) => + /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def; + const zip = (...arrays) => { + const maxLength = Math.max(...arrays.map(x => x.length)); + return Array.from({ length: maxLength }).map((_, i) => { + return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]); + }); +}; + const zipObject = (props, values) => + props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {}); + const zipWith = (...array) => { + const fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined; + return Array.from( + { length: Math.max(...array.map(a => a.length)) }, + (_, i) => (fn ? fn(...array.map(a => a[i])) : array.map(a => a[i])) + ); +}; -const stableSort = (arr, compare) => - arr - .map((item, index) => ({ item, index })) - .sort((a, b) => compare(a.item, b.item) || a.index - b.index) - .map(({ item }) => item); -const standardDeviation = (arr, usePopulation = false) => { - const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length; - return Math.sqrt( - arr.reduce((acc, val) => acc.concat((val - mean) ** 2), []).reduce((acc, val) => acc + val, 0) / - (arr.length - (usePopulation ? 0 : 1)) - ); -}; - -const stringPermutations = str => { - if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; - return str - .split('') - .reduce( - (acc, letter, i) => - acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), - [] - ); -}; - -const stripHTMLTags = str => str.replace(/<[^>]*>/g, ''); - -const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); - -const sumBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0); - -const sumPower = (end, power = 2, start = 1) => - Array(end + 1 - start) - .fill(0) - .map((x, i) => (i + start) ** power) - .reduce((a, b) => a + b, 0); - -const symmetricDifference = (a, b) => { - const sA = new Set(a), - sB = new Set(b); - return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; -}; - -const symmetricDifferenceBy = (a, b, fn) => { - const sA = new Set(a.map(v => fn(v))), - sB = new Set(b.map(v => fn(v))); - return [...a.filter(x => !sB.has(fn(x))), ...b.filter(x => !sA.has(fn(x)))]; -}; - -const symmetricDifferenceWith = (arr, val, comp) => [ - ...arr.filter(a => val.findIndex(b => comp(a, b)) === -1), - ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1) -]; - -const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); - -const take = (arr, n = 1) => arr.slice(0, n); - -const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); - -const takeRightWhile = (arr, func) => - arr.reduceRight((acc, el) => (func(el) ? acc : [el, ...acc]), []); - -const takeWhile = (arr, func) => { - for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i); - return arr; -}; - -const throttle = (fn, wait) => { - let inThrottle, lastFn, lastTime; - return function() { - const context = this, - args = arguments; - if (!inThrottle) { - fn.apply(context, args); - lastTime = Date.now(); - inThrottle = true; - } else { - clearTimeout(lastFn); - lastFn = setTimeout(function() { - if (Date.now() - lastTime >= wait) { - fn.apply(context, args); - lastTime = Date.now(); - } - }, wait - (Date.now() - lastTime)); - } - }; -}; - -const timeTaken = callback => { - console.time('timeTaken'); - const r = callback(); - console.timeEnd('timeTaken'); - return r; -}; - -const times = (n, fn, context = undefined) => { - let i = 0; - while (fn.call(context, i) !== false && ++i < n) {} -}; - -const toCamelCase = str => { - let s = - 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(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase()) - .join(''); - return s.slice(0, 1).toLowerCase() + s.slice(1); -}; - -const toCurrency = (n, curr, LanguageFormat = undefined) => - Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n); - -const toDecimalMark = num => num.toLocaleString('en-US'); - -const toHash = (object, key) => - Array.prototype.reduce.call( - object, - (acc, data, index) => ((acc[!key ? index : data[key]] = data), acc), - {} - ); - -const toKebabCase = str => - 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(x => x.toLowerCase()) - .join('-'); - -const toOrdinalSuffix = num => { - const int = parseInt(num), - digits = [int % 10, int % 100], - ordinals = ['st', 'nd', 'rd', 'th'], - oPattern = [1, 2, 3, 4], - tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19]; - return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) - ? int + ordinals[digits[0] - 1] - : int + ordinals[3]; -}; - -const toSafeInteger = num => - Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)); - -const toSnakeCase = str => - 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(x => x.toLowerCase()) - .join('_'); - -const toggleClass = (el, className) => el.classList.toggle(className); - -const tomorrow = (long = false) => { - let t = new Date(); - t.setDate(t.getDate() + 1); - const ret = `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String( - t.getDate() - ).padStart(2, '0')}`; - return !long ? ret : `${ret}T00:00:00`; -}; - -const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc); - -const triggerEvent = (el, eventType, detail) => - el.dispatchEvent(new CustomEvent(eventType, { detail })); - -const truncateString = (str, num) => - str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; - -const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]); - -const unary = fn => val => fn(val); - -const uncurry = (fn, n = 1) => (...args) => { - const next = acc => args => args.reduce((x, y) => x(y), acc); - if (n > args.length) throw new RangeError('Arguments too few!'); - return next(fn)(args.slice(0, n)); -}; - -const unescapeHTML = str => - str.replace( - /&|<|>|'|"/g, - tag => - ({ - '&': '&', - '<': '<', - '>': '>', - ''': "'", - '"': '"' - }[tag] || tag) - ); - -const unflattenObject = obj => - Object.keys(obj).reduce((acc, k) => { - if (k.indexOf('.') !== -1) { - const keys = k.split('.'); - Object.assign( - acc, - JSON.parse( - '{' + - keys.map((v, i) => (i !== keys.length - 1 ? `"${v}":{` : `"${v}":`)).join('') + - obj[k] + - '}'.repeat(keys.length) - ) - ); - } else acc[k] = obj[k]; - return acc; - }, {}); - -const unfold = (fn, seed) => { - let result = [], - val = [null, seed]; - while ((val = fn(val[1]))) result.push(val[0]); - return result; -}; - -const union = (a, b) => Array.from(new Set([...a, ...b])); - -const unionBy = (a, b, fn) => { - const s = new Set(a.map(v => fn(v))); - return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))])); -}; - -const unionWith = (a, b, comp) => - Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)])); - -const uniqueElements = arr => [...new Set(arr)]; - -const uniqueElementsBy = (arr, fn) => - arr.reduce((acc, v) => { - if (!acc.some(x => fn(v, x))) acc.push(v); - return acc; - }, []); - -const uniqueElementsByRight = (arr, fn) => - arr.reduceRight((acc, v) => { - if (!acc.some(x => fn(v, x))) acc.push(v); - return acc; - }, []); - -const uniqueSymmetricDifference = (a, b) => [ - ...new Set([...a.filter(v => !b.includes(v)), ...b.filter(v => !a.includes(v))]) -]; - -const untildify = str => str.replace(/^~($|\/|\\)/, `${typeof require !== "undefined" && require('os').homedir()}$1`); - -const unzip = arr => - arr.reduce( - (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), - Array.from({ - length: Math.max(...arr.map(x => x.length)) - }).map(x => []) - ); - -const unzipWith = (arr, fn) => - arr - .reduce( - (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), - Array.from({ - length: Math.max(...arr.map(x => x.length)) - }).map(x => []) - ) - .map(val => fn(...val)); - -const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; - -const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x); - -const without = (arr, ...args) => arr.filter(v => !args.includes(v)); - -const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); - -const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []); - -const yesNo = (val, def = false) => - /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def; - -const zip = (...arrays) => { - const maxLength = Math.max(...arrays.map(x => x.length)); - return Array.from({ length: maxLength }).map((_, i) => { - return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]); - }); -}; - -const zipObject = (props, values) => - props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {}); - -const zipWith = (...array) => { - const fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined; - return Array.from( - { length: Math.max(...array.map(a => a.length)) }, - (_, i) => (fn ? fn(...array.map(a => a[i])) : array.map(a => a[i])) - ); -}; - -export { CSVToArray, CSVToJSON, JSONToFile, JSONtoCSV, RGBToHex, URLJoin, UUIDGeneratorBrowser, UUIDGeneratorNode, all, allEqual, any, approximatelyEqual, arrayToCSV, arrayToHtmlList, ary, atob, attempt, average, averageBy, bifurcate, bifurcateBy, bind, bindAll, bindKey, binomialCoefficient, bottomVisible, btoa, byteSize, call, capitalize, capitalizeEveryWord, castArray, chainAsync, chunk, clampNumber, cloneRegExp, coalesce, coalesceFactory, collectInto, colorize, compact, compose, composeRight, converge, copyToClipboard, countBy, countOccurrences, counter, createElement, createEventHub, currentURL, curry, dayOfYear, debounce, decapitalize, deepClone, deepFlatten, deepFreeze, defaults, defer, degreesToRads, delay, detectDeviceType, difference, differenceBy, differenceWith, dig, digitize, distance, drop, dropRight, dropRightWhile, dropWhile, elementContains, elementIsVisibleInViewport, elo, equals, escapeHTML, escapeRegExp, everyNth, extendHex, factorial, fibonacci, filterNonUnique, filterNonUniqueBy, findKey, findLast, findLastIndex, findLastKey, flatten, flattenObject, flip, forEachRight, forOwn, forOwnRight, formatDuration, fromCamelCase, functionName, functions, gcd, geometricProgression, get, getColonTimeFromDate, getDaysDiffBetweenDates, getImages, getMeridiemSuffixOfInteger, getScrollPosition, getStyle, getType, getURLParameters, groupBy, hammingDistance, hasClass, hasFlags, hashBrowser, hashNode, head, hexToRGB, hide, httpGet, httpPost, httpsRedirect, hz, inRange, indentString, indexOfAll, initial, initialize2DArray, initializeArrayWithRange, initializeArrayWithRangeRight, initializeArrayWithValues, initializeNDArray, insertAfter, insertBefore, intersection, intersectionBy, intersectionWith, invertKeyValues, is, isAbsoluteURL, isAfterDate, isAnagram, isArrayLike, isBeforeDate, isBoolean, isBrowser, isBrowserTabFocused, isDivisible, isDuplexStream, isEmpty, isEven, isFunction, isLowerCase, isNil, isNull, isNumber, isObject, isObjectLike, isPlainObject, isPrime, isPrimitive, isPromiseLike, isReadableStream, isSameDate, isSorted, isStream, isString, isSymbol, isTravisCI, isUndefined, isUpperCase, isValidJSON, isWritableStream, join, last, lcm, longestItem, lowercaseKeys, luhnCheck, mapKeys, mapObject, mapString, mapValues, mask, matches, matchesWith, maxBy, maxDate, maxN, median, memoize, merge, minBy, minDate, minN, mostPerformant, negate, nest, nodeListToArray, none, nthArg, nthElement, objectFromPairs, objectToPairs, observeMutations, off, offset, omit, omitBy, on, onUserInputChange, once, orderBy, over, overArgs, pad, palindrome, parseCookie, partial, partialRight, partition, percentile, permutations, pick, pickBy, pipeAsyncFunctions, pipeFunctions, pluralize, powerset, prefix, prettyBytes, primes, promisify, pull, pullAtIndex, pullAtValue, pullBy, radsToDegrees, randomHexColorCode, randomIntArrayInRange, randomIntegerInRange, randomNumberInRange, readFileLines, rearg, recordAnimationFrames, redirect, reduceSuccessive, reduceWhich, reducedFilter, reject, remove, removeNonASCII, renameKeys, reverseString, round, runAsync, runPromisesInSeries, sample, sampleSize, scrollToTop, sdbm, serializeCookie, setStyle, shallowClone, shank, show, shuffle, similarity, size, sleep, smoothScroll, sortCharactersInString, sortedIndex, sortedIndexBy, sortedLastIndex, sortedLastIndexBy, splitLines, spreadOver, stableSort, standardDeviation, stringPermutations, stripHTMLTags, sum, sumBy, sumPower, symmetricDifference, symmetricDifferenceBy, symmetricDifferenceWith, tail, take, takeRight, takeRightWhile, takeWhile, throttle, timeTaken, times, toCamelCase, toCurrency, toDecimalMark, toHash, toKebabCase, toOrdinalSuffix, toSafeInteger, toSnakeCase, toggleClass, tomorrow, transform, triggerEvent, truncateString, truthCheckCollection, unary, uncurry, unescapeHTML, unflattenObject, unfold, union, unionBy, unionWith, uniqueElements, uniqueElementsBy, uniqueElementsByRight, uniqueSymmetricDifference, untildify, unzip, unzipWith, validateNumber, when, without, words, xProd, yesNo, zip, zipObject, zipWith }; +module.exports = {all,allEqual,any,approximatelyEqual,arrayToCSV,arrayToHtmlList,ary,atob,attempt,average,averageBy,bifurcate,bifurcateBy,bind,bindAll,bindKey,binomialCoefficient,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,composeRight,converge,copyToClipboard,countBy,counter,countOccurrences,createElement,createEventHub,CSVToArray,CSVToJSON,currentURL,curry,dayOfYear,debounce,decapitalize,deepClone,deepFlatten,deepFreeze,defaults,defer,degreesToRads,delay,detectDeviceType,difference,differenceBy,differenceWith,dig,digitize,distance,drop,dropRight,dropRightWhile,dropWhile,elementContains,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,filterNonUniqueBy,findKey,findLast,findLastIndex,findLastKey,flatten,flattenObject,flip,forEachRight,formatDuration,forOwn,forOwnRight,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getColonTimeFromDate,getDaysDiffBetweenDates,getImages,getMeridiemSuffixOfInteger,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,hz,indentString,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,initializeNDArray,inRange,insertAfter,insertBefore,intersection,intersectionBy,intersectionWith,invertKeyValues,is,isAbsoluteURL,isAfterDate,isAnagram,isArrayLike,isBeforeDate,isBoolean,isBrowser,isBrowserTabFocused,isDivisible,isDuplexStream,isEmpty,isEven,isFunction,isLowerCase,isNil,isNull,isNumber,isObject,isObjectLike,isPlainObject,isPrime,isPrimitive,isPromiseLike,isReadableStream,isSameDate,isSorted,isStream,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,isWritableStream,join,JSONtoCSV,JSONToFile,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapString,mapValues,mask,matches,matchesWith,maxBy,maxDate,maxN,median,memoize,merge,minBy,minDate,minN,mostPerformant,negate,nest,nodeListToArray,none,nthArg,nthElement,objectFromPairs,objectToPairs,observeMutations,off,offset,omit,omitBy,on,once,onUserInputChange,orderBy,over,overArgs,pad,palindrome,parseCookie,partial,partialRight,partition,percentile,permutations,pick,pickBy,pipeAsyncFunctions,pipeFunctions,pluralize,powerset,prefix,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,radsToDegrees,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,rearg,recordAnimationFrames,redirect,reducedFilter,reduceSuccessive,reduceWhich,reject,remove,removeNonASCII,renameKeys,reverseString,RGBToHex,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,serializeCookie,setStyle,shallowClone,shank,show,shuffle,similarity,size,sleep,smoothScroll,sortCharactersInString,sortedIndex,sortedIndexBy,sortedLastIndex,sortedLastIndexBy,splitLines,spreadOver,stableSort,standardDeviation,stringPermutations,stripHTMLTags,sum,sumBy,sumPower,symmetricDifference,symmetricDifferenceBy,symmetricDifferenceWith,tail,take,takeRight,takeRightWhile,takeWhile,throttle,times,timeTaken,toCamelCase,toCurrency,toDecimalMark,toggleClass,toHash,toKebabCase,tomorrow,toOrdinalSuffix,toSafeInteger,toSnakeCase,transform,triggerEvent,truncateString,truthCheckCollection,unary,uncurry,unescapeHTML,unflattenObject,unfold,union,unionBy,unionWith,uniqueElements,uniqueElementsBy,uniqueElementsByRight,uniqueSymmetricDifference,untildify,unzip,unzipWith,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,validateNumber,when,without,words,xProd,yesNo,zip,zipObject,zipWith}; diff --git a/dist/_30s.js b/dist/_30s.js index bfd04c12b..3af22678f 100644 --- a/dist/_30s.js +++ b/dist/_30s.js @@ -1,1997 +1,1332 @@ (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global._30s = {}))); -}(this, (function (exports) { 'use strict'; - - const CSVToArray = (data, delimiter = ',', omitFirstRow = false) => - data - .slice(omitFirstRow ? data.indexOf('\n') + 1 : 0) - .split('\n') - .map(v => v.split(delimiter)); - - const CSVToJSON = (data, delimiter = ',') => { - const titles = data.slice(0, data.indexOf('\n')).split(delimiter); - return data - .slice(data.indexOf('\n') + 1) - .split('\n') - .map(v => { - const values = v.split(delimiter); - return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {}); - }); - }; + typeof exports === 'object' && typeof module !== 'undefined' ? factory() : + typeof define === 'function' && define.amd ? define(factory) : + (factory()); +}(this, (function () { 'use strict'; + const crypto = typeof require !== "undefined" && require('crypto'); const fs = typeof require !== "undefined" && require('fs'); - const JSONToFile = (obj, filename) => - fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); - - const JSONtoCSV = (arr, columns, delimiter = ',') => - [ - columns.join(delimiter), - ...arr.map(obj => - columns.reduce( - (acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`, - '' - ) - ) - ].join('\n'); - - const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); - - const URLJoin = (...args) => - args - .join('/') - .replace(/[\/]+/g, '/') - .replace(/^(.+):\//, '$1://') - .replace(/^file:/, 'file:/') - .replace(/\/(\?|&|#[^!])/g, '$1') - .replace(/\?/g, '&') - .replace('&', '?'); - - 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 all = (arr, fn = Boolean) => arr.every(fn); - - const allEqual = arr => arr.every(val => val === arr[0]); - - const any = (arr, fn = Boolean) => arr.some(fn); - - const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon; - - const arrayToCSV = (arr, delimiter = ',') => - arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n'); - - const arrayToHtmlList = (arr, listID) => - (el => ( - (el = document.querySelector('#' + listID)), - (el.innerHTML += arr.map(item => `
  • ${item}
  • `).join('')) - ))(); - - const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); - - const atob = str => Buffer.from(str, 'base64').toString('binary'); - - const attempt = (fn, ...args) => { - try { - return fn(...args); - } catch (e) { - return e instanceof Error ? e : new Error(e); - } - }; - - const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length; - - const averageBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) / - arr.length; - - const bifurcate = (arr, filter) => - arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]); - - const bifurcateBy = (arr, fn) => - arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]); - - const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]); - - const bindAll = (obj, ...fns) => - fns.forEach( - fn => ( - (f = obj[fn]), - (obj[fn] = function() { - return f.apply(obj); - }) - ) - ); - - const bindKey = (context, fn, ...boundArgs) => (...args) => - context[fn].apply(context, [...boundArgs, ...args]); - - const binomialCoefficient = (n, k) => { - if (Number.isNaN(n) || Number.isNaN(k)) return NaN; - if (k < 0 || k > n) return 0; - if (k === 0 || k === n) return 1; - if (k === 1 || k === n - 1) return n; - if (n - k < k) k = n - k; - let res = n; - for (let j = 2; j <= k; j++) res *= (n - j + 1) / j; - return Math.round(res); - }; - - const bottomVisible = () => - document.documentElement.clientHeight + window.scrollY >= - (document.documentElement.scrollHeight || document.documentElement.clientHeight); - - const btoa = str => Buffer.from(str, 'binary').toString('base64'); - - const byteSize = str => new Blob([str]).size; + const all = (arr, fn = Boolean) => arr.every(fn); + const allEqual = arr => arr.every(val => val === arr[0]); + const any = (arr, fn = Boolean) => arr.some(fn); + const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon; + const arrayToCSV = (arr, delimiter = ',') => + arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n'); + const arrayToHtmlList = (arr, listID) => + (el => ( + (el = document.querySelector('#' + listID)), + (el.innerHTML += arr.map(item => `
  • ${item}
  • `).join('')) + ))(); + const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); + const atob = str => Buffer.from(str, 'base64').toString('binary'); + const attempt = (fn, ...args) => { + try { + return fn(...args); + } catch (e) { + return e instanceof Error ? e : new Error(e); + } + }; + const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length; + const averageBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) / + arr.length; + const bifurcate = (arr, filter) => + arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]); + const bifurcateBy = (arr, fn) => + arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]); + const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]); + const bindAll = (obj, ...fns) => + fns.forEach( + fn => ( + (f = obj[fn]), + (obj[fn] = function() { + return f.apply(obj); + }) + ) + ); + const bindKey = (context, fn, ...boundArgs) => (...args) => + context[fn].apply(context, [...boundArgs, ...args]); + const binomialCoefficient = (n, k) => { + if (Number.isNaN(n) || Number.isNaN(k)) return NaN; + if (k < 0 || k > n) return 0; + if (k === 0 || k === n) return 1; + if (k === 1 || k === n - 1) return n; + if (n - k < k) k = n - k; + let res = n; + for (let j = 2; j <= k; j++) res *= (n - j + 1) / j; + return Math.round(res); + }; + const bottomVisible = () => + document.documentElement.clientHeight + window.scrollY >= + (document.documentElement.scrollHeight || document.documentElement.clientHeight); + const btoa = str => Buffer.from(str, 'binary').toString('base64'); + const byteSize = str => new Blob([str]).size; const call = (key, ...args) => context => context[key](...args); - - const capitalize = ([first, ...rest], lowerRest = false) => - first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); - - const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); - - const castArray = val => (Array.isArray(val) ? val : [val]); - - const chainAsync = fns => { - let curr = 0; - const next = () => fns[curr++](next); - next(); - }; - - const chunk = (arr, size) => - Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => - arr.slice(i * size, i * size + size) - ); - - const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); - - const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags); - - const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); - - const coalesceFactory = valid => (...args) => args.find(valid); - + const capitalize = ([first, ...rest], lowerRest = false) => + first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); + const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); + const castArray = val => (Array.isArray(val) ? val : [val]); + const chainAsync = fns => { + let curr = 0; + const next = () => fns[curr++](next); + next(); + }; + const chunk = (arr, size) => + Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => + arr.slice(i * size, i * size + size) + ); + const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); + const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags); + const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); + const coalesceFactory = valid => (...args) => args.find(valid); const collectInto = fn => (...args) => fn(args); - - const colorize = (...args) => ({ - black: `\x1b[30m${args.join(' ')}`, - red: `\x1b[31m${args.join(' ')}`, - green: `\x1b[32m${args.join(' ')}`, - yellow: `\x1b[33m${args.join(' ')}`, - blue: `\x1b[34m${args.join(' ')}`, - magenta: `\x1b[35m${args.join(' ')}`, - cyan: `\x1b[36m${args.join(' ')}`, - white: `\x1b[37m${args.join(' ')}`, - bgBlack: `\x1b[40m${args.join(' ')}\x1b[0m`, - bgRed: `\x1b[41m${args.join(' ')}\x1b[0m`, - bgGreen: `\x1b[42m${args.join(' ')}\x1b[0m`, - bgYellow: `\x1b[43m${args.join(' ')}\x1b[0m`, - bgBlue: `\x1b[44m${args.join(' ')}\x1b[0m`, - bgMagenta: `\x1b[45m${args.join(' ')}\x1b[0m`, - bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`, - bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m` - }); - - const compact = arr => arr.filter(Boolean); - - const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); - - const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); - - const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args))); - - const copyToClipboard = str => { - const el = document.createElement('textarea'); - el.value = str; - el.setAttribute('readonly', ''); - el.style.position = 'absolute'; - el.style.left = '-9999px'; - document.body.appendChild(el); - const selected = - document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; - el.select(); - document.execCommand('copy'); - document.body.removeChild(el); - if (selected) { - document.getSelection().removeAllRanges(); - document.getSelection().addRange(selected); - } - }; - - const countBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { - acc[val] = (acc[val] || 0) + 1; - return acc; - }, {}); - - const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); - - const counter = (selector, start, end, step = 1, duration = 2000) => { - let current = start, - _step = (end - start) * step < 0 ? -step : step, - timer = setInterval(() => { - current += _step; - document.querySelector(selector).innerHTML = current; - if (current >= end) document.querySelector(selector).innerHTML = end; - if (current >= end) clearInterval(timer); - }, Math.abs(Math.floor(duration / (end - start)))); - return timer; - }; - - const createElement = str => { - const el = document.createElement('div'); - el.innerHTML = str; - return el.firstElementChild; - }; - - const createEventHub = () => ({ - hub: Object.create(null), - emit(event, data) { - (this.hub[event] || []).forEach(handler => handler(data)); - }, - on(event, handler) { - if (!this.hub[event]) this.hub[event] = []; - this.hub[event].push(handler); - }, - off(event, handler) { - const i = (this.hub[event] || []).findIndex(h => h === handler); - if (i > -1) this.hub[event].splice(i, 1); - } - }); - - const currentURL = () => window.location.href; - - const curry = (fn, arity = fn.length, ...args) => - arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args); - - const dayOfYear = date => - Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); - - const debounce = (fn, ms = 0) => { - let timeoutId; - return function(...args) { - clearTimeout(timeoutId); - timeoutId = setTimeout(() => fn.apply(this, args), ms); - }; - }; - - const decapitalize = ([first, ...rest], upperRest = false) => - first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join('')); - - const deepClone = obj => { - let clone = Object.assign({}, obj); - Object.keys(clone).forEach( - key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]) - ); - return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone; - }; - - const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); - - const deepFreeze = obj => - Object.keys(obj).forEach( - prop => - !obj[prop] instanceof Object || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop]) - ) || Object.freeze(obj); - - const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); - - const defer = (fn, ...args) => setTimeout(fn, 1, ...args); - - const degreesToRads = deg => (deg * Math.PI) / 180.0; - - const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args); - - const detectDeviceType = () => - /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) - ? 'Mobile' - : 'Desktop'; - - const difference = (a, b) => { - const s = new Set(b); - return a.filter(x => !s.has(x)); - }; - - const differenceBy = (a, b, fn) => { - const s = new Set(b.map(v => fn(v))); - return a.filter(x => !s.has(fn(x))); - }; - - const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1); - - const dig = (obj, target) => - target in obj - ? obj[target] - : Object.values(obj).reduce((acc, val) => { - if (acc !== undefined) return acc; - if (typeof val === 'object') return dig(val, target); - }, undefined); - - const digitize = n => [...`${n}`].map(i => parseInt(i)); - - const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); - - const drop = (arr, n = 1) => arr.slice(n); - - const dropRight = (arr, n = 1) => arr.slice(0, -n); - - const dropRightWhile = (arr, func) => { - while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1); - return arr; - }; - - const dropWhile = (arr, func) => { - while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); - return arr; - }; - - const elementContains = (parent, child) => parent !== child && parent.contains(child); - - const elementIsVisibleInViewport = (el, partiallyVisible = false) => { - const { top, left, bottom, right } = el.getBoundingClientRect(); - const { innerHeight, innerWidth } = window; - return partiallyVisible - ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && - ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) - : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; - }; - - const elo = ([...ratings], kFactor = 32, selfRating) => { - const [a, b] = ratings; - const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400)); - const newRating = (rating, i) => - (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a)); - if (ratings.length === 2) { - return [newRating(a, 1), newRating(b, 0)]; - } - for (let i = 0, len = ratings.length; i < len; i++) { - let j = i; - while (j < len - 1) { - j++; - [ratings[i], ratings[j]] = elo([ratings[i], ratings[j]], kFactor); - } - } - return ratings; - }; - - const equals = (a, b) => { - if (a === b) return true; - if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime(); - if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b; - if (a === null || a === undefined || b === null || b === undefined) return false; - if (a.prototype !== b.prototype) return false; - let keys = Object.keys(a); - if (keys.length !== Object.keys(b).length) return false; - return keys.every(k => equals(a[k], b[k])); - }; - - const escapeHTML = str => - str.replace( - /[&<>'"]/g, - tag => - ({ - '&': '&', - '<': '<', - '>': '>', - "'": ''', - '"': '"' - }[tag] || tag) - ); - - const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - - const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); - - const extendHex = shortHex => - '#' + - shortHex - .slice(shortHex.startsWith('#') ? 1 : 0) - .split('') - .map(x => x + x) - .join(''); - - const factorial = n => - n < 0 - ? (() => { - throw new TypeError('Negative numbers are not allowed!'); - })() - : n <= 1 - ? 1 - : n * factorial(n - 1); - - const fibonacci = n => - Array.from({ length: n }).reduce( - (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), - [] - ); - - const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); - - const filterNonUniqueBy = (arr, fn) => - arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j))); - - const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj)); - - const findLast = (arr, fn) => arr.filter(fn).pop(); - - const findLastIndex = (arr, fn) => - arr - .map((val, i) => [i, val]) - .filter(([i, val]) => fn(val, i, arr)) - .pop()[0]; - - const findLastKey = (obj, fn) => - Object.keys(obj) - .reverse() - .find(key => fn(obj[key], key, obj)); - - const flatten = (arr, depth = 1) => - arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []); - - const flattenObject = (obj, prefix = '') => - Object.keys(obj).reduce((acc, k) => { - const pre = prefix.length ? prefix + '.' : ''; - if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k)); - else acc[pre + k] = obj[k]; - return acc; - }, {}); - + const colorize = (...args) => ({ + black: `\x1b[30m${args.join(' ')}`, + red: `\x1b[31m${args.join(' ')}`, + green: `\x1b[32m${args.join(' ')}`, + yellow: `\x1b[33m${args.join(' ')}`, + blue: `\x1b[34m${args.join(' ')}`, + magenta: `\x1b[35m${args.join(' ')}`, + cyan: `\x1b[36m${args.join(' ')}`, + white: `\x1b[37m${args.join(' ')}`, + bgBlack: `\x1b[40m${args.join(' ')}\x1b[0m`, + bgRed: `\x1b[41m${args.join(' ')}\x1b[0m`, + bgGreen: `\x1b[42m${args.join(' ')}\x1b[0m`, + bgYellow: `\x1b[43m${args.join(' ')}\x1b[0m`, + bgBlue: `\x1b[44m${args.join(' ')}\x1b[0m`, + bgMagenta: `\x1b[45m${args.join(' ')}\x1b[0m`, + bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`, + bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m` + }); + const compact = arr => arr.filter(Boolean); + const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); + const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); + const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args))); + const copyToClipboard = str => { + const el = document.createElement('textarea'); + el.value = str; + el.setAttribute('readonly', ''); + el.style.position = 'absolute'; + el.style.left = '-9999px'; + document.body.appendChild(el); + const selected = + document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; + el.select(); + document.execCommand('copy'); + document.body.removeChild(el); + if (selected) { + document.getSelection().removeAllRanges(); + document.getSelection().addRange(selected); + } + }; + const countBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => { + acc[val] = (acc[val] || 0) + 1; + return acc; + }, {}); + const counter = (selector, start, end, step = 1, duration = 2000) => { + let current = start, + _step = (end - start) * step < 0 ? -step : step, + timer = setInterval(() => { + current += _step; + document.querySelector(selector).innerHTML = current; + if (current >= end) document.querySelector(selector).innerHTML = end; + if (current >= end) clearInterval(timer); + }, Math.abs(Math.floor(duration / (end - start)))); + return timer; + }; + const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); + const createElement = str => { + const el = document.createElement('div'); + el.innerHTML = str; + return el.firstElementChild; + }; + const createEventHub = () => ({ + hub: Object.create(null), + emit(event, data) { + (this.hub[event] || []).forEach(handler => handler(data)); + }, + on(event, handler) { + if (!this.hub[event]) this.hub[event] = []; + this.hub[event].push(handler); + }, + off(event, handler) { + const i = (this.hub[event] || []).findIndex(h => h === handler); + if (i > -1) this.hub[event].splice(i, 1); + } + }); + const CSVToArray = (data, delimiter = ',', omitFirstRow = false) => + data + .slice(omitFirstRow ? data.indexOf('\n') + 1 : 0) + .split('\n') + .map(v => v.split(delimiter)); + const CSVToJSON = (data, delimiter = ',') => { + const titles = data.slice(0, data.indexOf('\n')).split(delimiter); + return data + .slice(data.indexOf('\n') + 1) + .split('\n') + .map(v => { + const values = v.split(delimiter); + return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {}); + }); + }; + const currentURL = () => window.location.href; + const curry = (fn, arity = fn.length, ...args) => + arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args); + const dayOfYear = date => + Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); + const debounce = (fn, ms = 0) => { + let timeoutId; + return function(...args) { + clearTimeout(timeoutId); + timeoutId = setTimeout(() => fn.apply(this, args), ms); + }; + }; + const decapitalize = ([first, ...rest], upperRest = false) => + first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join('')); + const deepClone = obj => { + let clone = Object.assign({}, obj); + Object.keys(clone).forEach( + key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]) + ); + return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone; + }; + const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); + const deepFreeze = obj => + Object.keys(obj).forEach( + prop => + !(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop]) + ) || Object.freeze(obj); + const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); + const defer = (fn, ...args) => setTimeout(fn, 1, ...args); + const degreesToRads = deg => (deg * Math.PI) / 180.0; + const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args); + const detectDeviceType = () => + /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) + ? 'Mobile' + : 'Desktop'; + const difference = (a, b) => { + const s = new Set(b); + return a.filter(x => !s.has(x)); + }; + const differenceBy = (a, b, fn) => { + const s = new Set(b.map(fn)); + return a.filter(x => !s.has(fn(x))); + }; + const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1); + const dig = (obj, target) => + target in obj + ? obj[target] + : Object.values(obj).reduce((acc, val) => { + if (acc !== undefined) return acc; + if (typeof val === 'object') return dig(val, target); + }, undefined); + const digitize = n => [...`${n}`].map(i => parseInt(i)); + const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); + const drop = (arr, n = 1) => arr.slice(n); + const dropRight = (arr, n = 1) => arr.slice(0, -n); + const dropRightWhile = (arr, func) => { + while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1); + return arr; + }; + const dropWhile = (arr, func) => { + while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); + return arr; + }; + const elementContains = (parent, child) => parent !== child && parent.contains(child); + const elementIsVisibleInViewport = (el, partiallyVisible = false) => { + const { top, left, bottom, right } = el.getBoundingClientRect(); + const { innerHeight, innerWidth } = window; + return partiallyVisible + ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && + ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) + : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; + }; + const elo = ([...ratings], kFactor = 32, selfRating) => { + const [a, b] = ratings; + const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400)); + const newRating = (rating, i) => + (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a)); + if (ratings.length === 2) return [newRating(a, 1), newRating(b, 0)]; + + for (let i = 0, len = ratings.length; i < len; i++) { + let j = i; + while (j < len - 1) { + j++; + [ratings[i], ratings[j]] = elo([ratings[i], ratings[j]], kFactor); + } + } + return ratings; + }; + const equals = (a, b) => { + if (a === b) return true; + if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime(); + if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b; + if (a === null || a === undefined || b === null || b === undefined) return false; + if (a.prototype !== b.prototype) return false; + let keys = Object.keys(a); + if (keys.length !== Object.keys(b).length) return false; + return keys.every(k => equals(a[k], b[k])); + }; + const escapeHTML = str => + str.replace( + /[&<>'"]/g, + tag => + ({ + '&': '&', + '<': '<', + '>': '>', + "'": ''', + '"': '"' + }[tag] || tag) + ); + const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); + const extendHex = shortHex => + '#' + + shortHex + .slice(shortHex.startsWith('#') ? 1 : 0) + .split('') + .map(x => x + x) + .join(''); + const factorial = n => + n < 0 + ? (() => { + throw new TypeError('Negative numbers are not allowed!'); + })() + : n <= 1 + ? 1 + : n * factorial(n - 1); + const fibonacci = n => + Array.from({ length: n }).reduce( + (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), + [] + ); + const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); + const filterNonUniqueBy = (arr, fn) => + arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j))); + const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj)); + const findLast = (arr, fn) => arr.filter(fn).pop(); + const findLastIndex = (arr, fn) => + arr + .map((val, i) => [i, val]) + .filter(([i, val]) => fn(val, i, arr)) + .pop()[0]; + const findLastKey = (obj, fn) => + Object.keys(obj) + .reverse() + .find(key => fn(obj[key], key, obj)); + const flatten = (arr, depth = 1) => + arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []); + const flattenObject = (obj, prefix = '') => + Object.keys(obj).reduce((acc, k) => { + const pre = prefix.length ? prefix + '.' : ''; + if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k)); + else acc[pre + k] = obj[k]; + return acc; + }, {}); const flip = fn => (first, ...rest) => fn(...rest, first); - - const forEachRight = (arr, callback) => - arr - .slice(0) - .reverse() - .forEach(callback); - - const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj)); - - const forOwnRight = (obj, fn) => - Object.keys(obj) - .reverse() - .forEach(key => fn(obj[key], key, obj)); - - const formatDuration = ms => { - if (ms < 0) ms = -ms; - const time = { - day: Math.floor(ms / 86400000), - hour: Math.floor(ms / 3600000) % 24, - minute: Math.floor(ms / 60000) % 60, - second: Math.floor(ms / 1000) % 60, - millisecond: Math.floor(ms) % 1000 - }; - return Object.entries(time) - .filter(val => val[1] !== 0) - .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`) - .join(', '); - }; - - const fromCamelCase = (str, separator = '_') => - str - .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') - .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2') - .toLowerCase(); - - const functionName = fn => (console.debug(fn.name), fn); - - const functions = (obj, inherited = false) => - (inherited - ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))] - : Object.keys(obj) - ).filter(key => typeof obj[key] === 'function'); - - const gcd = (...arr) => { - const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); - return [...arr].reduce((a, b) => _gcd(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 get = (from, ...selectors) => - [...selectors].map(s => - s - .replace(/\[([^\[\]]*)\]/g, '.$1.') - .split('.') - .filter(t => t !== '') - .reduce((prev, cur) => prev && prev[cur], from) - ); - - const getColonTimeFromDate = date => date.toTimeString().slice(0, 8); - - const getDaysDiffBetweenDates = (dateInitial, dateFinal) => - (dateFinal - dateInitial) / (1000 * 3600 * 24); - - const getImages = (el, includeDuplicates = false) => { - const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src')); - return includeDuplicates ? images : [...new Set(images)]; - }; - - const getMeridiemSuffixOfInteger = num => - num === 0 || num === 24 - ? 12 + 'am' - : num === 12 - ? 12 + 'pm' - : num < 12 - ? (num % 12) + 'am' - : (num % 12) + 'pm'; - - const getScrollPosition = (el = window) => ({ - x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, - y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop - }); - - const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]; - - const getType = v => - v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase(); - - const getURLParameters = url => - (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( - (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), - {} - ); - - const groupBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { - acc[val] = (acc[val] || []).concat(arr[i]); - return acc; - }, {}); - - const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length; - - const hasClass = (el, className) => el.classList.contains(className); - - const hasFlags = (...flags) => - flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag)); - - const hashBrowser = val => - crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => { - let hexes = [], - view = new DataView(h); - for (let i = 0; i < view.byteLength; i += 4) - hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8)); - return hexes.join(''); - }); - - const crypto$2 = typeof require !== "undefined" && require('crypto'); - const hashNode = val => - new Promise(resolve => - setTimeout( - () => - resolve( - crypto$2 - .createHash('sha256') - .update(val) - .digest('hex') - ), - 0 - ) - ); - - const head = arr => arr[0]; - - const hexToRGB = hex => { - let alpha = false, - h = hex.slice(hex.startsWith('#') ? 1 : 0); - if (h.length === 3) h = [...h].map(x => x + x).join(''); - else if (h.length === 8) alpha = true; - h = parseInt(h, 16); - return ( - 'rgb' + - (alpha ? 'a' : '') + - '(' + - (h >>> (alpha ? 24 : 16)) + - ', ' + - ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) + - ', ' + - ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) + - (alpha ? `, ${h & 0x000000ff}` : '') + - ')' - ); - }; - - const hide = els => els.forEach(e => (e.style.display = 'none')); - - const httpGet = (url, callback, err = console.error) => { - const request = new XMLHttpRequest(); - request.open('GET', url, true); - request.onload = () => callback(request.responseText); - request.onerror = () => err(request); - request.send(); - }; - - const httpPost = (url, data, callback, err = console.error) => { - const request = new XMLHttpRequest(); - request.open('POST', url, true); - request.setRequestHeader('Content-type', 'application/json; charset=utf-8'); - request.onload = () => callback(request.responseText); - request.onerror = () => err(request); - request.send(data); - }; - - const httpsRedirect = () => { - if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); - }; - - const hz = (fn, iterations = 100) => { - const before = performance.now(); - for (let i = 0; i < iterations; i++) fn(); - return (1000 * iterations) / (performance.now() - before); - }; - - const inRange = (n, start, end = null) => { - if (end && start > end) [end, start] = [start, end]; - return end == null ? n >= 0 && n < start : n >= start && n < end; - }; - - const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count)); - - const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []); - - const initial = arr => arr.slice(0, -1); - - const initialize2DArray = (w, h, val = null) => - Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val)); - - const initializeArrayWithRange = (end, start = 0, step = 1) => - Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) => i * step + start); - - const initializeArrayWithRangeRight = (end, start = 0, step = 1) => - Array.from({ length: Math.ceil((end + 1 - start) / step) }).map( - (v, i, arr) => (arr.length - i - 1) * step + start - ); - - const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); - - const initializeNDArray = (val, ...args) => - args.length === 0 - ? val - : Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1))); - - const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString); - - const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString); - - const intersection = (a, b) => { - const s = new Set(b); - return a.filter(x => s.has(x)); - }; - - const intersectionBy = (a, b, fn) => { - const s = new Set(b.map(fn)); - return a.filter(x => s.has(fn(x))); - }; - - const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1); - - const invertKeyValues = (obj, fn) => - Object.keys(obj).reduce((acc, key) => { - const val = fn ? fn(obj[key]) : obj[key]; - acc[val] = acc[val] || []; - acc[val].push(key); - return acc; - }, {}); - - const is = (type, val) => ![, null].includes(val) && val.constructor === type; - - const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); - - const isAfterDate = (dateA, dateB) => dateA > dateB; - - const isAnagram = (str1, str2) => { - const normalize = str => - str - .toLowerCase() - .replace(/[^a-z0-9]/gi, '') - .split('') - .sort() - .join(''); - return normalize(str1) === normalize(str2); - }; - - const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function'; - - const isBeforeDate = (dateA, dateB) => dateA < dateB; - - const isBoolean = val => typeof val === 'boolean'; - - const isBrowser = () => ![typeof window, typeof document].includes('undefined'); - - const isBrowserTabFocused = () => !document.hidden; - - const isDivisible = (dividend, divisor) => dividend % divisor === 0; - - const isDuplexStream = val => - val !== null && - typeof val === 'object' && - typeof val.pipe === 'function' && - typeof val._read === 'function' && - typeof val._readableState === 'object' && - typeof val._write === 'function' && - typeof val._writableState === 'object'; - - const isEmpty = val => val == null || !(Object.keys(val) || val).length; - - const isEven = num => num % 2 === 0; - - const isFunction = val => typeof val === 'function'; - - const isLowerCase = str => str === str.toLowerCase(); - - const isNil = val => val === undefined || val === null; - - const isNull = val => val === null; - - const isNumber = val => typeof val === 'number'; - - const isObject = obj => obj === Object(obj); - - const isObjectLike = val => val !== null && typeof val === 'object'; - - const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object; - - 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 isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null; - - const isPromiseLike = obj => - obj !== null && - (typeof obj === 'object' || typeof obj === 'function') && - typeof obj.then === 'function'; - - const isReadableStream = val => - val !== null && - typeof val === 'object' && - typeof val.pipe === 'function' && - typeof val._read === 'function' && - typeof val._readableState === 'object'; - - const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString(); - - const isSorted = arr => { - let direction = -(arr[0] - arr[1]); - for (let [i, val] of arr.entries()) { - direction = !direction ? -(arr[i - 1] - arr[i]) : direction; - if (i === arr.length - 1) return !direction ? 0 : direction; - else if ((val - arr[i + 1]) * direction > 0) return 0; - } - }; - - const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function'; - - const isString = val => typeof val === 'string'; - - const isSymbol = val => typeof val === 'symbol'; - - const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; - - const isUndefined = val => val === undefined; - - const isUpperCase = str => str === str.toUpperCase(); - - const isValidJSON = obj => { - try { - JSON.parse(obj); - return true; - } catch (e) { - return false; - } - }; - - const isWritableStream = val => - val !== null && - typeof val === 'object' && - typeof val.pipe === 'function' && - typeof val._write === 'function' && - typeof val._writableState === 'object'; - - const join = (arr, separator = ',', end = separator) => - arr.reduce( - (acc, val, i) => - i === arr.length - 2 - ? acc + val + end - : i === arr.length - 1 - ? acc + val - : acc + val + separator, - '' - ); - - const last = arr => arr[arr.length - 1]; - - const lcm = (...arr) => { - const gcd = (x, y) => (!y ? x : gcd(y, x % y)); - const _lcm = (x, y) => (x * y) / gcd(x, y); - return [...arr].reduce((a, b) => _lcm(a, b)); - }; - - const longestItem = (val, ...vals) => - [val, ...vals].reduce((a, x) => (x.length > a.length ? x : a)); - - const lowercaseKeys = obj => - Object.keys(obj).reduce((acc, key) => { - acc[key.toLowerCase()] = obj[key]; - return acc; - }, {}); - - const luhnCheck = num => { - let arr = (num + '') - .split('') - .reverse() - .map(x => parseInt(x)); - let lastDigit = arr.splice(0, 1)[0]; - let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9), 0); - sum += lastDigit; - return sum % 10 === 0; - }; - - const mapKeys = (obj, fn) => - Object.keys(obj).reduce((acc, k) => { - acc[fn(obj[k], k, obj)] = obj[k]; - return acc; - }, {}); - - const mapObject = (arr, fn) => - (a => ( - (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) - ))(); - - const mapString = (str, fn) => - str - .split('') - .map((c, i) => fn(c, i, str)) - .join(''); - - const mapValues = (obj, fn) => - Object.keys(obj).reduce((acc, k) => { - acc[k] = fn(obj[k], k, obj); - return acc; - }, {}); - - const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask); - - const matches = (obj, source) => - Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]); - - const matchesWith = (obj, source, fn) => - Object.keys(source).every( - key => - obj.hasOwnProperty(key) && fn - ? fn(obj[key], source[key], key, obj, source) - : obj[key] == source[key] - ); - - const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); - - const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates)); - - const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); - - const median = arr => { - const mid = Math.floor(arr.length / 2), - nums = [...arr].sort((a, b) => a - b); - return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; - }; - - const memoize = fn => { - const cache = new Map(); - const cached = function(val) { - return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val); - }; - cached.cache = cache; - return cached; - }; - - const merge = (...objs) => - [...objs].reduce( - (acc, obj) => - Object.keys(obj).reduce((a, k) => { - acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k]; - return acc; - }, {}), - {} - ); - - const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); - - const minDate = (...dates) => new Date(Math.min.apply(null, ...dates)); - - const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); - - const mostPerformant = (fns, iterations = 10000) => { - const times = fns.map(fn => { - const before = performance.now(); - for (let i = 0; i < iterations; i++) fn(); - return performance.now() - before; - }); - return times.indexOf(Math.min(...times)); - }; - - const negate = func => (...args) => !func(...args); - - const nest = (items, id = null, link = 'parent_id') => - items - .filter(item => item[link] === id) - .map(item => ({ ...item, children: nest(items, item.id) })); - - const nodeListToArray = nodeList => [...nodeList]; - - const none = (arr, fn = Boolean) => !arr.some(fn); - - const nthArg = n => (...args) => args.slice(n)[0]; - - const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0]; - - const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {}); - - const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); - - const observeMutations = (element, callback, options) => { - const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m))); - observer.observe( - element, - Object.assign( - { - childList: true, - attributes: true, - attributeOldValue: true, - characterData: true, - characterDataOldValue: true, - subtree: true - }, - options - ) - ); - return observer; - }; - - const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); - - const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)]; - - const omit = (obj, arr) => - Object.keys(obj) - .filter(k => !arr.includes(k)) - .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); - - const omitBy = (obj, fn) => - Object.keys(obj) - .filter(k => !fn(obj[k], k)) - .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); - - const on = (el, evt, fn, opts = {}) => { - const delegatorFn = e => e.target.matches(opts.target) && fn.call(e.target, e); - el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false); - if (opts.target) return delegatorFn; - }; - - const onUserInputChange = callback => { - let type = 'mouse', - lastTime = 0; - const mousemoveHandler = () => { - const now = performance.now(); - if (now - lastTime < 20) - (type = 'mouse'), callback(type), document.removeEventListener('mousemove', mousemoveHandler); - lastTime = now; - }; - document.addEventListener('touchstart', () => { - if (type === 'touch') return; - (type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler); - }); - }; - - 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) => { - if (acc === 0) { - const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]]; - acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0; - } - return acc; - }, 0) - ); - - const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); - - const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val))); - - const pad = (str, length, char = ' ') => - str.padStart((str.length + length) / 2, char).padEnd(length, char); - - const palindrome = str => { - const s = str.toLowerCase().replace(/[\W_]/g, ''); - return s === [...s].reverse().join(''); - }; - - const parseCookie = str => - str - .split(';') - .map(v => v.split('=')) - .reduce((acc, v) => { - acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim()); - return acc; - }, {}); - - const partial = (fn, ...partials) => (...args) => fn(...partials, ...args); - - const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials); - - const partition = (arr, fn) => - arr.reduce( - (acc, val, i, arr) => { - acc[fn(val, i, arr) ? 0 : 1].push(val); - return acc; - }, - [[], []] - ); - - const percentile = (arr, val) => - (100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0)) / arr.length; - - const permutations = arr => { - if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr; - return arr.reduce( - (acc, item, i) => - acc.concat( - permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val]) - ), - [] - ); - }; - - const pick = (obj, arr) => - arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); - - const pickBy = (obj, fn) => - Object.keys(obj) - .filter(k => fn(obj[k], k)) - .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); - - const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); - - const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); - - const pluralize = (val, word, plural = word + 's') => { - const _pluralize = (num, word, plural = word + 's') => - [1, -1].includes(Number(num)) ? word : plural; - if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]); - return _pluralize(val, word, plural); - }; - - const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); - - const prefix = prop => { - const capitalizedProp = prop.charAt(0).toUpperCase() + prop.slice(1); - const prefixes = ['', 'webkit', 'moz', 'ms', 'o']; - const i = prefixes.findIndex( - prefix => typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !== 'undefined' - ); - return i !== -1 ? (i === 0 ? prop : prefixes[i] + capitalizedProp) : null; - }; - - const prettyBytes = (num, precision = 3, addSpace = true) => { - const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0]; - const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1); - const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision)); - return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent]; - }; - - const primes = num => { - let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2), - sqroot = Math.floor(Math.sqrt(num)), - numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2); - numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x))); - return arr; - }; - - const promisify = func => (...args) => - new Promise((resolve, reject) => - func(...args, (err, result) => (err ? reject(err) : resolve(result))) - ); - - const pull = (arr, ...args) => { - let argState = Array.isArray(args[0]) ? args[0] : args; - let pulled = arr.filter((v, i) => !argState.includes(v)); - arr.length = 0; - pulled.forEach(v => arr.push(v)); - }; - - const pullAtIndex = (arr, pullArr) => { - let removed = []; - let pulled = arr - .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v)) - .filter((v, i) => !pullArr.includes(i)); - arr.length = 0; - pulled.forEach(v => arr.push(v)); - return removed; - }; - - const pullAtValue = (arr, pullArr) => { - let removed = [], - pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)), - mutateTo = arr.filter((v, i) => !pullArr.includes(v)); - arr.length = 0; - mutateTo.forEach(v => arr.push(v)); - return removed; - }; - - const pullBy = (arr, ...args) => { - const length = args.length; - let fn = length > 1 ? args[length - 1] : undefined; - fn = typeof fn == 'function' ? (args.pop(), fn) : undefined; - let argState = (Array.isArray(args[0]) ? args[0] : args).map(val => fn(val)); - let pulled = arr.filter((v, i) => !argState.includes(fn(v))); - arr.length = 0; - pulled.forEach(v => arr.push(v)); - }; - - const radsToDegrees = rad => (rad * 180.0) / Math.PI; - - const randomHexColorCode = () => { - let n = (Math.random() * 0xfffff * 1000000).toString(16); - return '#' + n.slice(0, 6); - }; - - const randomIntArrayInRange = (min, max, n = 1) => - Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); - - const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; - - const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; - - const fs$1 = typeof require !== "undefined" && require('fs'); - const readFileLines = filename => - fs$1 - .readFileSync(filename) - .toString('UTF8') - .split('\n'); - - const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i])); - - const recordAnimationFrames = (callback, autoStart = true) => { - let running = true, - raf; - const stop = () => { - running = false; - cancelAnimationFrame(raf); - }; - const start = () => { - running = true; - run(); - }; - const run = () => { - raf = requestAnimationFrame(() => { - callback(); - if (running) run(); - }); - }; - if (autoStart) start(); - return { start, stop }; - }; - - const redirect = (url, asLink = true) => - asLink ? (window.location.href = url) : window.location.replace(url); - - const reduceSuccessive = (arr, fn, acc) => - arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]); - - const reduceWhich = (arr, comparator = (a, b) => a - b) => - arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a)); - - const reducedFilter = (data, keys, fn) => - data.filter(fn).map(el => - keys.reduce((acc, key) => { - acc[key] = el[key]; - return acc; - }, {}) - ); - - const reject = (pred, array) => array.filter((...args) => !pred(...args)); - - const remove = (arr, func) => - Array.isArray(arr) - ? arr.filter(func).reduce((acc, val) => { - arr.splice(arr.indexOf(val), 1); - return acc.concat(val); - }, []) - : []; - - const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); - - const renameKeys = (keysMap, obj) => - Object.keys(obj).reduce( - (acc, key) => ({ - ...acc, - ...{ [keysMap[key] || key]: obj[key] } - }), - {} - ); - - const reverseString = str => [...str].reverse().join(''); - - const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); - - const runAsync = fn => { - const worker = new Worker( - URL.createObjectURL(new Blob([`postMessage((${fn})());`]), { - type: 'application/javascript; charset=utf-8' - }) - ); - return new Promise((res, rej) => { - worker.onmessage = ({ data }) => { - res(data), worker.terminate(); - }; - worker.onerror = err => { - rej(err), worker.terminate(); - }; - }); - }; - - const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); - - const sample = arr => arr[Math.floor(Math.random() * arr.length)]; - - const sampleSize = ([...arr], n = 1) => { - let m = arr.length; - while (m) { - const i = Math.floor(Math.random() * m--); - [arr[m], arr[i]] = [arr[i], arr[m]]; - } - return arr.slice(0, n); - }; - - const scrollToTop = () => { - const c = document.documentElement.scrollTop || document.body.scrollTop; - if (c > 0) { - window.requestAnimationFrame(scrollToTop); - window.scrollTo(0, c - c / 8); - } - }; - - const sdbm = str => { - let arr = str.split(''); - return arr.reduce( - (hashCode, currentVal) => - (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode), - 0 - ); - }; - - const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; - - const setStyle = (el, ruleName, val) => (el.style[ruleName] = val); - - const shallowClone = obj => Object.assign({}, obj); - - const shank = (arr, index = 0, delCount = 0, ...elements) => - arr - .slice(0, index) - .concat(elements) - .concat(arr.slice(index + delCount)); - - const show = (...el) => [...el].forEach(e => (e.style.display = '')); - - const shuffle = ([...arr]) => { - let m = arr.length; - while (m) { - const i = Math.floor(Math.random() * m--); - [arr[m], arr[i]] = [arr[i], arr[m]]; - } - return arr; - }; - - const similarity = (arr, values) => arr.filter(v => values.includes(v)); - - const size = val => - Array.isArray(val) - ? val.length - : val && typeof val === 'object' - ? val.size || val.length || Object.keys(val).length - : typeof val === 'string' - ? new Blob([val]).size - : 0; - - const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); - - const smoothScroll = element => - document.querySelector(element).scrollIntoView({ - behavior: 'smooth' - }); - - const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join(''); - - const sortedIndex = (arr, n) => { - const isDescending = arr[0] > arr[arr.length - 1]; - const index = arr.findIndex(el => (isDescending ? n >= el : n <= el)); - return index === -1 ? arr.length : index; - }; - - const sortedIndexBy = (arr, n, fn) => { - const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); - const val = fn(n); - const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el))); - return index === -1 ? arr.length : index; - }; - - const sortedLastIndex = (arr, n) => { - const isDescending = arr[0] > arr[arr.length - 1]; - const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el)); - return index === -1 ? 0 : arr.length - index; - }; - - const sortedLastIndexBy = (arr, n, fn) => { - const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); - const val = fn(n); - const index = arr - .map(fn) - .reverse() - .findIndex(el => (isDescending ? val <= el : val >= el)); - return index === -1 ? 0 : arr.length - index; - }; - - const splitLines = str => str.split(/\r?\n/); - + const forEachRight = (arr, callback) => + arr + .slice(0) + .reverse() + .forEach(callback); + const formatDuration = ms => { + if (ms < 0) ms = -ms; + const time = { + day: Math.floor(ms / 86400000), + hour: Math.floor(ms / 3600000) % 24, + minute: Math.floor(ms / 60000) % 60, + second: Math.floor(ms / 1000) % 60, + millisecond: Math.floor(ms) % 1000 + }; + return Object.entries(time) + .filter(val => val[1] !== 0) + .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`) + .join(', '); + }; + const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj)); + const forOwnRight = (obj, fn) => + Object.keys(obj) + .reverse() + .forEach(key => fn(obj[key], key, obj)); + const fromCamelCase = (str, separator = '_') => + str + .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') + .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2') + .toLowerCase(); + const functionName = fn => (console.debug(fn.name), fn); + const functions = (obj, inherited = false) => + (inherited + ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))] + : Object.keys(obj) + ).filter(key => typeof obj[key] === 'function'); + const gcd = (...arr) => { + const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); + return [...arr].reduce((a, b) => _gcd(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 get = (from, ...selectors) => + [...selectors].map(s => + s + .replace(/\[([^\[\]]*)\]/g, '.$1.') + .split('.') + .filter(t => t !== '') + .reduce((prev, cur) => prev && prev[cur], from) + ); + const getColonTimeFromDate = date => date.toTimeString().slice(0, 8); + const getDaysDiffBetweenDates = (dateInitial, dateFinal) => + (dateFinal - dateInitial) / (1000 * 3600 * 24); + const getImages = (el, includeDuplicates = false) => { + const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src')); + return includeDuplicates ? images : [...new Set(images)]; + }; + const getMeridiemSuffixOfInteger = num => + num === 0 || num === 24 + ? 12 + 'am' + : num === 12 + ? 12 + 'pm' + : num < 12 + ? (num % 12) + 'am' + : (num % 12) + 'pm'; + const getScrollPosition = (el = window) => ({ + x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, + y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop + }); + const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]; + const getType = v => + v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase(); + const getURLParameters = url => + (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( + (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), + {} + ); + const groupBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { + acc[val] = (acc[val] || []).concat(arr[i]); + return acc; + }, {}); + const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length; + const hasClass = (el, className) => el.classList.contains(className); + const hasFlags = (...flags) => + flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag)); + const hashBrowser = val => + crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => { + let hexes = [], + view = new DataView(h); + for (let i = 0; i < view.byteLength; i += 4) + hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8)); + return hexes.join(''); + }); + + const hashNode = val => + new Promise(resolve => + setTimeout( + () => + resolve( + crypto + .createHash('sha256') + .update(val) + .digest('hex') + ), + 0 + ) + ); + const head = arr => arr[0]; + const hexToRGB = hex => { + let alpha = false, + h = hex.slice(hex.startsWith('#') ? 1 : 0); + if (h.length === 3) h = [...h].map(x => x + x).join(''); + else if (h.length === 8) alpha = true; + h = parseInt(h, 16); + return ( + 'rgb' + + (alpha ? 'a' : '') + + '(' + + (h >>> (alpha ? 24 : 16)) + + ', ' + + ((h & (alpha ? 0x00ff0000 : 0x00ff00)) >>> (alpha ? 16 : 8)) + + ', ' + + ((h & (alpha ? 0x0000ff00 : 0x0000ff)) >>> (alpha ? 8 : 0)) + + (alpha ? `, ${h & 0x000000ff}` : '') + + ')' + ); + }; + const hide = els => els.forEach(e => (e.style.display = 'none')); + const httpGet = (url, callback, err = console.error) => { + const request = new XMLHttpRequest(); + request.open('GET', url, true); + request.onload = () => callback(request.responseText); + request.onerror = () => err(request); + request.send(); + }; + const httpPost = (url, data, callback, err = console.error) => { + const request = new XMLHttpRequest(); + request.open('POST', url, true); + request.setRequestHeader('Content-type', 'application/json; charset=utf-8'); + request.onload = () => callback(request.responseText); + request.onerror = () => err(request); + request.send(data); + }; + const httpsRedirect = () => { + if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); + }; + const hz = (fn, iterations = 100) => { + const before = performance.now(); + for (let i = 0; i < iterations; i++) fn(); + return (1000 * iterations) / (performance.now() - before); + }; + const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count)); + const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []); + const initial = arr => arr.slice(0, -1); + const initialize2DArray = (w, h, val = null) => + Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val)); + const initializeArrayWithRange = (end, start = 0, step = 1) => + Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) => i * step + start); + const initializeArrayWithRangeRight = (end, start = 0, step = 1) => + Array.from({ length: Math.ceil((end + 1 - start) / step) }).map( + (v, i, arr) => (arr.length - i - 1) * step + start + ); + const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); + const initializeNDArray = (val, ...args) => + args.length === 0 + ? val + : Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1))); + const inRange = (n, start, end = null) => { + if (end && start > end) [end, start] = [start, end]; + return end == null ? n >= 0 && n < start : n >= start && n < end; + }; + const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString); + const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString); + const intersection = (a, b) => { + const s = new Set(b); + return a.filter(x => s.has(x)); + }; + const intersectionBy = (a, b, fn) => { + const s = new Set(b.map(fn)); + return a.filter(x => s.has(fn(x))); + }; + const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1); + const invertKeyValues = (obj, fn) => + Object.keys(obj).reduce((acc, key) => { + const val = fn ? fn(obj[key]) : obj[key]; + acc[val] = acc[val] || []; + acc[val].push(key); + return acc; + }, {}); + const is = (type, val) => ![, null].includes(val) && val.constructor === type; + const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); + const isAfterDate = (dateA, dateB) => dateA > dateB; + const isAnagram = (str1, str2) => { + const normalize = str => + str + .toLowerCase() + .replace(/[^a-z0-9]/gi, '') + .split('') + .sort() + .join(''); + return normalize(str1) === normalize(str2); + }; + const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function'; + const isBeforeDate = (dateA, dateB) => dateA < dateB; + const isBoolean = val => typeof val === 'boolean'; + const isBrowser = () => ![typeof window, typeof document].includes('undefined'); + const isBrowserTabFocused = () => !document.hidden; + const isDivisible = (dividend, divisor) => dividend % divisor === 0; + const isDuplexStream = val => + val !== null && + typeof val === 'object' && + typeof val.pipe === 'function' && + typeof val._read === 'function' && + typeof val._readableState === 'object' && + typeof val._write === 'function' && + typeof val._writableState === 'object'; + const isEmpty = val => val == null || !(Object.keys(val) || val).length; + const isEven = num => num % 2 === 0; + const isFunction = val => typeof val === 'function'; + const isLowerCase = str => str === str.toLowerCase(); + const isNil = val => val === undefined || val === null; + const isNull = val => val === null; + const isNumber = val => typeof val === 'number'; + const isObject = obj => obj === Object(obj); + const isObjectLike = val => val !== null && typeof val === 'object'; + const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object; + 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 isPrimitive = val => Object(val) !== val; + const isPromiseLike = obj => + obj !== null && + (typeof obj === 'object' || typeof obj === 'function') && + typeof obj.then === 'function'; + const isReadableStream = val => + val !== null && + typeof val === 'object' && + typeof val.pipe === 'function' && + typeof val._read === 'function' && + typeof val._readableState === 'object'; + const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString(); + const isSorted = arr => { + let direction = -(arr[0] - arr[1]); + for (let [i, val] of arr.entries()) { + direction = !direction ? -(arr[i - 1] - arr[i]) : direction; + if (i === arr.length - 1) return !direction ? 0 : direction; + else if ((val - arr[i + 1]) * direction > 0) return 0; + } + }; + const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function'; + const isString = val => typeof val === 'string'; + const isSymbol = val => typeof val === 'symbol'; + const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; + const isUndefined = val => val === undefined; + const isUpperCase = str => str === str.toUpperCase(); + const isValidJSON = obj => { + try { + JSON.parse(obj); + return true; + } catch (e) { + return false; + } + }; + const isWritableStream = val => + val !== null && + typeof val === 'object' && + typeof val.pipe === 'function' && + typeof val._write === 'function' && + typeof val._writableState === 'object'; + const join = (arr, separator = ',', end = separator) => + arr.reduce( + (acc, val, i) => + i === arr.length - 2 + ? acc + val + end + : i === arr.length - 1 + ? acc + val + : acc + val + separator, + '' + ); + const JSONtoCSV = (arr, columns, delimiter = ',') => + [ + columns.join(delimiter), + ...arr.map(obj => + columns.reduce( + (acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`, + '' + ) + ) + ].join('\n'); + + const JSONToFile = (obj, filename) => + fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); + const last = arr => arr[arr.length - 1]; + const lcm = (...arr) => { + const gcd = (x, y) => (!y ? x : gcd(y, x % y)); + const _lcm = (x, y) => (x * y) / gcd(x, y); + return [...arr].reduce((a, b) => _lcm(a, b)); + }; + const longestItem = (val, ...vals) => + [val, ...vals].reduce((a, x) => (x.length > a.length ? x : a)); + const lowercaseKeys = obj => + Object.keys(obj).reduce((acc, key) => { + acc[key.toLowerCase()] = obj[key]; + return acc; + }, {}); + const luhnCheck = num => { + let arr = (num + '') + .split('') + .reverse() + .map(x => parseInt(x)); + let lastDigit = arr.splice(0, 1)[0]; + let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9), 0); + sum += lastDigit; + return sum % 10 === 0; + }; + const mapKeys = (obj, fn) => + Object.keys(obj).reduce((acc, k) => { + acc[fn(obj[k], k, obj)] = obj[k]; + return acc; + }, {}); + const mapObject = (arr, fn) => + (a => ( + (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) + ))(); + const mapString = (str, fn) => + str + .split('') + .map((c, i) => fn(c, i, str)) + .join(''); + const mapValues = (obj, fn) => + Object.keys(obj).reduce((acc, k) => { + acc[k] = fn(obj[k], k, obj); + return acc; + }, {}); + const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask); + const matches = (obj, source) => + Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]); + const matchesWith = (obj, source, fn) => + Object.keys(source).every( + key => + obj.hasOwnProperty(key) && fn + ? fn(obj[key], source[key], key, obj, source) + : obj[key] == source[key] + ); + const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); + const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates)); + const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); + const median = arr => { + const mid = Math.floor(arr.length / 2), + nums = [...arr].sort((a, b) => a - b); + return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; + }; + const memoize = fn => { + const cache = new Map(); + const cached = function(val) { + return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val); + }; + cached.cache = cache; + return cached; + }; + const merge = (...objs) => + [...objs].reduce( + (acc, obj) => + Object.keys(obj).reduce((a, k) => { + acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k]; + return acc; + }, {}), + {} + ); + const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); + const minDate = (...dates) => new Date(Math.min.apply(null, ...dates)); + const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); + const mostPerformant = (fns, iterations = 10000) => { + const times = fns.map(fn => { + const before = performance.now(); + for (let i = 0; i < iterations; i++) fn(); + return performance.now() - before; + }); + return times.indexOf(Math.min(...times)); + }; + const negate = func => (...args) => !func(...args); + const nest = (items, id = null, link = 'parent_id') => + items + .filter(item => item[link] === id) + .map(item => ({ ...item, children: nest(items, item.id) })); + const nodeListToArray = nodeList => [...nodeList]; + const none = (arr, fn = Boolean) => !arr.some(fn); + const nthArg = n => (...args) => args.slice(n)[0]; + const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0]; + const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {}); + const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); + const observeMutations = (element, callback, options) => { + const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m))); + observer.observe( + element, + Object.assign( + { + childList: true, + attributes: true, + attributeOldValue: true, + characterData: true, + characterDataOldValue: true, + subtree: true + }, + options + ) + ); + return observer; + }; + const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); + const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)]; + const omit = (obj, arr) => + Object.keys(obj) + .filter(k => !arr.includes(k)) + .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); + const omitBy = (obj, fn) => + Object.keys(obj) + .filter(k => !fn(obj[k], k)) + .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); + const on = (el, evt, fn, opts = {}) => { + const delegatorFn = e => e.target.matches(opts.target) && fn.call(e.target, e); + el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false); + if (opts.target) return delegatorFn; + }; + 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; + const mousemoveHandler = () => { + const now = performance.now(); + if (now - lastTime < 20) + (type = 'mouse'), callback(type), document.removeEventListener('mousemove', mousemoveHandler); + lastTime = now; + }; + document.addEventListener('touchstart', () => { + if (type === 'touch') return; + (type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler); + }); + }; + const orderBy = (arr, props, orders) => + [...arr].sort((a, b) => + props.reduce((acc, prop, i) => { + if (acc === 0) { + const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]]; + acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0; + } + return acc; + }, 0) + ); + const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); + const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val))); + const pad = (str, length, char = ' ') => + str.padStart((str.length + length) / 2, char).padEnd(length, char); + const palindrome = str => { + const s = str.toLowerCase().replace(/[\W_]/g, ''); + return s === [...s].reverse().join(''); + }; + const parseCookie = str => + str + .split(';') + .map(v => v.split('=')) + .reduce((acc, v) => { + acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim()); + return acc; + }, {}); + const partial = (fn, ...partials) => (...args) => fn(...partials, ...args); + const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials); + const partition = (arr, fn) => + arr.reduce( + (acc, val, i, arr) => { + acc[fn(val, i, arr) ? 0 : 1].push(val); + return acc; + }, + [[], []] + ); + const percentile = (arr, val) => + (100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0)) / arr.length; + const permutations = arr => { + if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr; + return arr.reduce( + (acc, item, i) => + acc.concat( + permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val => [item, ...val]) + ), + [] + ); + }; + const pick = (obj, arr) => + arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); + const pickBy = (obj, fn) => + Object.keys(obj) + .filter(k => fn(obj[k], k)) + .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); + const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); + const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); + const pluralize = (val, word, plural = word + 's') => { + const _pluralize = (num, word, plural = word + 's') => + [1, -1].includes(Number(num)) ? word : plural; + if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]); + return _pluralize(val, word, plural); + }; + const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); + const prefix = prop => { + const capitalizedProp = prop.charAt(0).toUpperCase() + prop.slice(1); + const prefixes = ['', 'webkit', 'moz', 'ms', 'o']; + const i = prefixes.findIndex( + prefix => typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !== 'undefined' + ); + return i !== -1 ? (i === 0 ? prop : prefixes[i] + capitalizedProp) : null; + }; + const prettyBytes = (num, precision = 3, addSpace = true) => { + const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0]; + const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1); + const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision)); + return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent]; + }; + const primes = num => { + let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2), + sqroot = Math.floor(Math.sqrt(num)), + numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2); + numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x))); + return arr; + }; + const promisify = func => (...args) => + new Promise((resolve, reject) => + func(...args, (err, result) => (err ? reject(err) : resolve(result))) + ); + const pull = (arr, ...args) => { + let argState = Array.isArray(args[0]) ? args[0] : args; + let pulled = arr.filter((v, i) => !argState.includes(v)); + arr.length = 0; + pulled.forEach(v => arr.push(v)); + }; + const pullAtIndex = (arr, pullArr) => { + let removed = []; + let pulled = arr + .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v)) + .filter((v, i) => !pullArr.includes(i)); + arr.length = 0; + pulled.forEach(v => arr.push(v)); + return removed; + }; + const pullAtValue = (arr, pullArr) => { + let removed = [], + pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)), + mutateTo = arr.filter((v, i) => !pullArr.includes(v)); + arr.length = 0; + mutateTo.forEach(v => arr.push(v)); + return removed; + }; + const pullBy = (arr, ...args) => { + const length = args.length; + let fn = length > 1 ? args[length - 1] : undefined; + fn = typeof fn == 'function' ? (args.pop(), fn) : undefined; + let argState = (Array.isArray(args[0]) ? args[0] : args).map(val => fn(val)); + let pulled = arr.filter((v, i) => !argState.includes(fn(v))); + arr.length = 0; + pulled.forEach(v => arr.push(v)); + }; + const radsToDegrees = rad => (rad * 180.0) / Math.PI; + const randomHexColorCode = () => { + let n = (Math.random() * 0xfffff * 1000000).toString(16); + return '#' + n.slice(0, 6); + }; + const randomIntArrayInRange = (min, max, n = 1) => + Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); + const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; + const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; + + const readFileLines = filename => + fs + .readFileSync(filename) + .toString('UTF8') + .split('\n'); + const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i])); + const recordAnimationFrames = (callback, autoStart = true) => { + let running = true, + raf; + const stop = () => { + running = false; + cancelAnimationFrame(raf); + }; + const start = () => { + running = true; + run(); + }; + const run = () => { + raf = requestAnimationFrame(() => { + callback(); + if (running) run(); + }); + }; + if (autoStart) start(); + return { start, stop }; + }; + const redirect = (url, asLink = true) => + asLink ? (window.location.href = url) : window.location.replace(url); + const reducedFilter = (data, keys, fn) => + data.filter(fn).map(el => + keys.reduce((acc, key) => { + acc[key] = el[key]; + return acc; + }, {}) + ); + const reduceSuccessive = (arr, fn, acc) => + arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]); + const reduceWhich = (arr, comparator = (a, b) => a - b) => + arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a)); + const reject = (pred, array) => array.filter((...args) => !pred(...args)); + const remove = (arr, func) => + Array.isArray(arr) + ? arr.filter(func).reduce((acc, val) => { + arr.splice(arr.indexOf(val), 1); + return acc.concat(val); + }, []) + : []; + const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); + const renameKeys = (keysMap, obj) => + Object.keys(obj).reduce( + (acc, key) => ({ + ...acc, + ...{ [keysMap[key] || key]: obj[key] } + }), + {} + ); + const reverseString = str => [...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 => { + const worker = new Worker( + URL.createObjectURL(new Blob([`postMessage((${fn})());`]), { + type: 'application/javascript; charset=utf-8' + }) + ); + return new Promise((res, rej) => { + worker.onmessage = ({ data }) => { + res(data), worker.terminate(); + }; + worker.onerror = err => { + rej(err), worker.terminate(); + }; + }); + }; + const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); + const sample = arr => arr[Math.floor(Math.random() * arr.length)]; + const sampleSize = ([...arr], n = 1) => { + let m = arr.length; + while (m) { + const i = Math.floor(Math.random() * m--); + [arr[m], arr[i]] = [arr[i], arr[m]]; + } + return arr.slice(0, n); + }; + const scrollToTop = () => { + const c = document.documentElement.scrollTop || document.body.scrollTop; + if (c > 0) { + window.requestAnimationFrame(scrollToTop); + window.scrollTo(0, c - c / 8); + } + }; + const sdbm = str => { + let arr = str.split(''); + return arr.reduce( + (hashCode, currentVal) => + (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode), + 0 + ); + }; + const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; + const setStyle = (el, ruleName, val) => (el.style[ruleName] = val); + const shallowClone = obj => Object.assign({}, obj); + const shank = (arr, index = 0, delCount = 0, ...elements) => + arr + .slice(0, index) + .concat(elements) + .concat(arr.slice(index + delCount)); + const show = (...el) => [...el].forEach(e => (e.style.display = '')); + const shuffle = ([...arr]) => { + let m = arr.length; + while (m) { + const i = Math.floor(Math.random() * m--); + [arr[m], arr[i]] = [arr[i], arr[m]]; + } + return arr; + }; + const similarity = (arr, values) => arr.filter(v => values.includes(v)); + const size = val => + Array.isArray(val) + ? val.length + : val && typeof val === 'object' + ? val.size || val.length || Object.keys(val).length + : typeof val === 'string' + ? new Blob([val]).size + : 0; + const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + const smoothScroll = element => + document.querySelector(element).scrollIntoView({ + behavior: 'smooth' + }); + const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join(''); + const sortedIndex = (arr, n) => { + const isDescending = arr[0] > arr[arr.length - 1]; + const index = arr.findIndex(el => (isDescending ? n >= el : n <= el)); + return index === -1 ? arr.length : index; + }; + const sortedIndexBy = (arr, n, fn) => { + const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); + const val = fn(n); + const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el))); + return index === -1 ? arr.length : index; + }; + const sortedLastIndex = (arr, n) => { + const isDescending = arr[0] > arr[arr.length - 1]; + const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el)); + return index === -1 ? 0 : arr.length - index; + }; + const sortedLastIndexBy = (arr, n, fn) => { + const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); + const val = fn(n); + const index = arr + .map(fn) + .reverse() + .findIndex(el => (isDescending ? val <= el : val >= el)); + return index === -1 ? 0 : arr.length - index; + }; + const splitLines = str => str.split(/\r?\n/); const spreadOver = fn => argsArr => fn(...argsArr); + const stableSort = (arr, compare) => + arr + .map((item, index) => ({ item, index })) + .sort((a, b) => compare(a.item, b.item) || a.index - b.index) + .map(({ item }) => item); + const standardDeviation = (arr, usePopulation = false) => { + const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length; + return Math.sqrt( + arr.reduce((acc, val) => acc.concat((val - mean) ** 2), []).reduce((acc, val) => acc + val, 0) / + (arr.length - (usePopulation ? 0 : 1)) + ); + }; + const stringPermutations = str => { + if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; + return str + .split('') + .reduce( + (acc, letter, i) => + acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), + [] + ); + }; + const stripHTMLTags = str => str.replace(/<[^>]*>/g, ''); + const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); + const sumBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0); + const sumPower = (end, power = 2, start = 1) => + Array(end + 1 - start) + .fill(0) + .map((x, i) => (i + start) ** power) + .reduce((a, b) => a + b, 0); + const symmetricDifference = (a, b) => { + const sA = new Set(a), + sB = new Set(b); + return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; + }; + const symmetricDifferenceBy = (a, b, fn) => { + const sA = new Set(a.map(v => fn(v))), + sB = new Set(b.map(v => fn(v))); + return [...a.filter(x => !sB.has(fn(x))), ...b.filter(x => !sA.has(fn(x)))]; + }; + const symmetricDifferenceWith = (arr, val, comp) => [ + ...arr.filter(a => val.findIndex(b => comp(a, b)) === -1), + ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1) + ]; + const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); + const take = (arr, n = 1) => arr.slice(0, n); + const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); + const takeRightWhile = (arr, func) => + arr.reduceRight((acc, el) => (func(el) ? acc : [el, ...acc]), []); + const takeWhile = (arr, func) => { + for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i); + return arr; + }; + const throttle = (fn, wait) => { + let inThrottle, lastFn, lastTime; + return function() { + const context = this, + args = arguments; + if (!inThrottle) { + fn.apply(context, args); + lastTime = Date.now(); + inThrottle = true; + } else { + clearTimeout(lastFn); + lastFn = setTimeout(function() { + if (Date.now() - lastTime >= wait) { + fn.apply(context, args); + lastTime = Date.now(); + } + }, Math.max(wait - (Date.now() - lastTime), 0)); + } + }; + }; + const times = (n, fn, context = undefined) => { + let i = 0; + while (fn.call(context, i) !== false && ++i < n) {} + }; + const timeTaken = callback => { + console.time('timeTaken'); + const r = callback(); + console.timeEnd('timeTaken'); + return r; + }; + const toCamelCase = str => { + let s = + 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(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase()) + .join(''); + return s.slice(0, 1).toLowerCase() + s.slice(1); + }; + const toCurrency = (n, curr, LanguageFormat = undefined) => + Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n); + const toDecimalMark = num => num.toLocaleString('en-US'); + const toggleClass = (el, className) => el.classList.toggle(className); + const toHash = (object, key) => + Array.prototype.reduce.call( + object, + (acc, data, index) => ((acc[!key ? index : data[key]] = data), acc), + {} + ); + const toKebabCase = str => + 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(x => x.toLowerCase()) + .join('-'); + const tomorrow = (long = false) => { + let t = new Date(); + t.setDate(t.getDate() + 1); + const ret = `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String( + t.getDate() + ).padStart(2, '0')}`; + return !long ? ret : `${ret}T00:00:00`; + }; + const toOrdinalSuffix = num => { + const int = parseInt(num), + digits = [int % 10, int % 100], + ordinals = ['st', 'nd', 'rd', 'th'], + oPattern = [1, 2, 3, 4], + tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19]; + return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) + ? int + ordinals[digits[0] - 1] + : int + ordinals[3]; + }; + const toSafeInteger = num => + Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)); + const toSnakeCase = str => + 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(x => x.toLowerCase()) + .join('_'); + const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc); + const triggerEvent = (el, eventType, detail) => + el.dispatchEvent(new CustomEvent(eventType, { detail })); + const truncateString = (str, num) => + str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; + const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]); + const unary = fn => val => fn(val); + const uncurry = (fn, n = 1) => (...args) => { + const next = acc => args => args.reduce((x, y) => x(y), acc); + if (n > args.length) throw new RangeError('Arguments too few!'); + return next(fn)(args.slice(0, n)); + }; + const unescapeHTML = str => + str.replace( + /&|<|>|'|"/g, + tag => + ({ + '&': '&', + '<': '<', + '>': '>', + ''': "'", + '"': '"' + }[tag] || tag) + ); + const unflattenObject = obj => + Object.keys(obj).reduce((acc, k) => { + if (k.indexOf('.') !== -1) { + const keys = k.split('.'); + Object.assign( + acc, + JSON.parse( + '{' + + keys.map((v, i) => (i !== keys.length - 1 ? `"${v}":{` : `"${v}":`)).join('') + + obj[k] + + '}'.repeat(keys.length) + ) + ); + } else acc[k] = obj[k]; + return acc; + }, {}); + const unfold = (fn, seed) => { + let result = [], + val = [null, seed]; + while ((val = fn(val[1]))) result.push(val[0]); + return result; + }; + const union = (a, b) => Array.from(new Set([...a, ...b])); + const unionBy = (a, b, fn) => { + const s = new Set(a.map(fn)); + return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))])); + }; + const unionWith = (a, b, comp) => + Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)])); + const uniqueElements = arr => [...new Set(arr)]; + const uniqueElementsBy = (arr, fn) => + arr.reduce((acc, v) => { + if (!acc.some(x => fn(v, x))) acc.push(v); + return acc; + }, []); + const uniqueElementsByRight = (arr, fn) => + arr.reduceRight((acc, v) => { + if (!acc.some(x => fn(v, x))) acc.push(v); + return acc; + }, []); + const uniqueSymmetricDifference = (a, b) => [ + ...new Set([...a.filter(v => !b.includes(v)), ...b.filter(v => !a.includes(v))]) + ]; + const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`); + const unzip = arr => + arr.reduce( + (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), + Array.from({ + length: Math.max(...arr.map(x => x.length)) + }).map(x => []) + ); + const unzipWith = (arr, fn) => + arr + .reduce( + (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), + Array.from({ + length: Math.max(...arr.map(x => x.length)) + }).map(x => []) + ) + .map(val => fn(...val)); + const URLJoin = (...args) => + args + .join('/') + .replace(/[\/]+/g, '/') + .replace(/^(.+):\//, '$1://') + .replace(/^file:/, 'file:/') + .replace(/\/(\?|&|#[^!])/g, '$1') + .replace(/\?/g, '&') + .replace('&', '?'); + const UUIDGeneratorBrowser = () => + ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => + (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16) + ); + + const UUIDGeneratorNode = () => + ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => + (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16) + ); + const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; + const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x); + const without = (arr, ...args) => arr.filter(v => !args.includes(v)); + const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); + const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []); + const yesNo = (val, def = false) => + /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def; + const zip = (...arrays) => { + const maxLength = Math.max(...arrays.map(x => x.length)); + return Array.from({ length: maxLength }).map((_, i) => { + return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]); + }); + }; + const zipObject = (props, values) => + props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {}); + const zipWith = (...array) => { + const fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined; + return Array.from( + { length: Math.max(...array.map(a => a.length)) }, + (_, i) => (fn ? fn(...array.map(a => a[i])) : array.map(a => a[i])) + ); + }; - const stableSort = (arr, compare) => - arr - .map((item, index) => ({ item, index })) - .sort((a, b) => compare(a.item, b.item) || a.index - b.index) - .map(({ item }) => item); - const standardDeviation = (arr, usePopulation = false) => { - const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length; - return Math.sqrt( - arr.reduce((acc, val) => acc.concat((val - mean) ** 2), []).reduce((acc, val) => acc + val, 0) / - (arr.length - (usePopulation ? 0 : 1)) - ); - }; - - const stringPermutations = str => { - if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; - return str - .split('') - .reduce( - (acc, letter, i) => - acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), - [] - ); - }; - - const stripHTMLTags = str => str.replace(/<[^>]*>/g, ''); - - const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); - - const sumBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0); - - const sumPower = (end, power = 2, start = 1) => - Array(end + 1 - start) - .fill(0) - .map((x, i) => (i + start) ** power) - .reduce((a, b) => a + b, 0); - - const symmetricDifference = (a, b) => { - const sA = new Set(a), - sB = new Set(b); - return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; - }; - - const symmetricDifferenceBy = (a, b, fn) => { - const sA = new Set(a.map(v => fn(v))), - sB = new Set(b.map(v => fn(v))); - return [...a.filter(x => !sB.has(fn(x))), ...b.filter(x => !sA.has(fn(x)))]; - }; - - const symmetricDifferenceWith = (arr, val, comp) => [ - ...arr.filter(a => val.findIndex(b => comp(a, b)) === -1), - ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1) - ]; - - const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); - - const take = (arr, n = 1) => arr.slice(0, n); - - const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); - - const takeRightWhile = (arr, func) => - arr.reduceRight((acc, el) => (func(el) ? acc : [el, ...acc]), []); - - const takeWhile = (arr, func) => { - for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i); - return arr; - }; - - const throttle = (fn, wait) => { - let inThrottle, lastFn, lastTime; - return function() { - const context = this, - args = arguments; - if (!inThrottle) { - fn.apply(context, args); - lastTime = Date.now(); - inThrottle = true; - } else { - clearTimeout(lastFn); - lastFn = setTimeout(function() { - if (Date.now() - lastTime >= wait) { - fn.apply(context, args); - lastTime = Date.now(); - } - }, wait - (Date.now() - lastTime)); - } - }; - }; - - const timeTaken = callback => { - console.time('timeTaken'); - const r = callback(); - console.timeEnd('timeTaken'); - return r; - }; - - const times = (n, fn, context = undefined) => { - let i = 0; - while (fn.call(context, i) !== false && ++i < n) {} - }; - - const toCamelCase = str => { - let s = - 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(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase()) - .join(''); - return s.slice(0, 1).toLowerCase() + s.slice(1); - }; - - const toCurrency = (n, curr, LanguageFormat = undefined) => - Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n); - - const toDecimalMark = num => num.toLocaleString('en-US'); - - const toHash = (object, key) => - Array.prototype.reduce.call( - object, - (acc, data, index) => ((acc[!key ? index : data[key]] = data), acc), - {} - ); - - const toKebabCase = str => - 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(x => x.toLowerCase()) - .join('-'); - - const toOrdinalSuffix = num => { - const int = parseInt(num), - digits = [int % 10, int % 100], - ordinals = ['st', 'nd', 'rd', 'th'], - oPattern = [1, 2, 3, 4], - tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19]; - return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) - ? int + ordinals[digits[0] - 1] - : int + ordinals[3]; - }; - - const toSafeInteger = num => - Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)); - - const toSnakeCase = str => - 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(x => x.toLowerCase()) - .join('_'); - - const toggleClass = (el, className) => el.classList.toggle(className); - - const tomorrow = (long = false) => { - let t = new Date(); - t.setDate(t.getDate() + 1); - const ret = `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String( - t.getDate() - ).padStart(2, '0')}`; - return !long ? ret : `${ret}T00:00:00`; - }; - - const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc); - - const triggerEvent = (el, eventType, detail) => - el.dispatchEvent(new CustomEvent(eventType, { detail })); - - const truncateString = (str, num) => - str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; - - const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]); - - const unary = fn => val => fn(val); - - const uncurry = (fn, n = 1) => (...args) => { - const next = acc => args => args.reduce((x, y) => x(y), acc); - if (n > args.length) throw new RangeError('Arguments too few!'); - return next(fn)(args.slice(0, n)); - }; - - const unescapeHTML = str => - str.replace( - /&|<|>|'|"/g, - tag => - ({ - '&': '&', - '<': '<', - '>': '>', - ''': "'", - '"': '"' - }[tag] || tag) - ); - - const unflattenObject = obj => - Object.keys(obj).reduce((acc, k) => { - if (k.indexOf('.') !== -1) { - const keys = k.split('.'); - Object.assign( - acc, - JSON.parse( - '{' + - keys.map((v, i) => (i !== keys.length - 1 ? `"${v}":{` : `"${v}":`)).join('') + - obj[k] + - '}'.repeat(keys.length) - ) - ); - } else acc[k] = obj[k]; - return acc; - }, {}); - - const unfold = (fn, seed) => { - let result = [], - val = [null, seed]; - while ((val = fn(val[1]))) result.push(val[0]); - return result; - }; - - const union = (a, b) => Array.from(new Set([...a, ...b])); - - const unionBy = (a, b, fn) => { - const s = new Set(a.map(v => fn(v))); - return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))])); - }; - - const unionWith = (a, b, comp) => - Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)])); - - const uniqueElements = arr => [...new Set(arr)]; - - const uniqueElementsBy = (arr, fn) => - arr.reduce((acc, v) => { - if (!acc.some(x => fn(v, x))) acc.push(v); - return acc; - }, []); - - const uniqueElementsByRight = (arr, fn) => - arr.reduceRight((acc, v) => { - if (!acc.some(x => fn(v, x))) acc.push(v); - return acc; - }, []); - - const uniqueSymmetricDifference = (a, b) => [ - ...new Set([...a.filter(v => !b.includes(v)), ...b.filter(v => !a.includes(v))]) - ]; - - const untildify = str => str.replace(/^~($|\/|\\)/, `${typeof require !== "undefined" && require('os').homedir()}$1`); - - const unzip = arr => - arr.reduce( - (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), - Array.from({ - length: Math.max(...arr.map(x => x.length)) - }).map(x => []) - ); - - const unzipWith = (arr, fn) => - arr - .reduce( - (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), - Array.from({ - length: Math.max(...arr.map(x => x.length)) - }).map(x => []) - ) - .map(val => fn(...val)); - - const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; - - const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x); - - const without = (arr, ...args) => arr.filter(v => !args.includes(v)); - - const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); - - const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []); - - const yesNo = (val, def = false) => - /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def; - - const zip = (...arrays) => { - const maxLength = Math.max(...arrays.map(x => x.length)); - return Array.from({ length: maxLength }).map((_, i) => { - return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]); - }); - }; - - const zipObject = (props, values) => - props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {}); - - const zipWith = (...array) => { - const fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined; - return Array.from( - { length: Math.max(...array.map(a => a.length)) }, - (_, i) => (fn ? fn(...array.map(a => a[i])) : array.map(a => a[i])) - ); - }; - - exports.CSVToArray = CSVToArray; - exports.CSVToJSON = CSVToJSON; - exports.JSONToFile = JSONToFile; - exports.JSONtoCSV = JSONtoCSV; - exports.RGBToHex = RGBToHex; - exports.URLJoin = URLJoin; - exports.UUIDGeneratorBrowser = UUIDGeneratorBrowser; - exports.UUIDGeneratorNode = UUIDGeneratorNode; - exports.all = all; - exports.allEqual = allEqual; - exports.any = any; - exports.approximatelyEqual = approximatelyEqual; - exports.arrayToCSV = arrayToCSV; - exports.arrayToHtmlList = arrayToHtmlList; - exports.ary = ary; - exports.atob = atob; - exports.attempt = attempt; - exports.average = average; - exports.averageBy = averageBy; - exports.bifurcate = bifurcate; - exports.bifurcateBy = bifurcateBy; - exports.bind = bind; - exports.bindAll = bindAll; - exports.bindKey = bindKey; - exports.binomialCoefficient = binomialCoefficient; - exports.bottomVisible = bottomVisible; - exports.btoa = btoa; - exports.byteSize = byteSize; - exports.call = call; - exports.capitalize = capitalize; - exports.capitalizeEveryWord = capitalizeEveryWord; - exports.castArray = castArray; - exports.chainAsync = chainAsync; - exports.chunk = chunk; - exports.clampNumber = clampNumber; - exports.cloneRegExp = cloneRegExp; - exports.coalesce = coalesce; - exports.coalesceFactory = coalesceFactory; - exports.collectInto = collectInto; - exports.colorize = colorize; - exports.compact = compact; - exports.compose = compose; - exports.composeRight = composeRight; - exports.converge = converge; - exports.copyToClipboard = copyToClipboard; - exports.countBy = countBy; - exports.countOccurrences = countOccurrences; - exports.counter = counter; - exports.createElement = createElement; - exports.createEventHub = createEventHub; - exports.currentURL = currentURL; - exports.curry = curry; - exports.dayOfYear = dayOfYear; - exports.debounce = debounce; - exports.decapitalize = decapitalize; - exports.deepClone = deepClone; - exports.deepFlatten = deepFlatten; - exports.deepFreeze = deepFreeze; - exports.defaults = defaults; - exports.defer = defer; - exports.degreesToRads = degreesToRads; - exports.delay = delay; - exports.detectDeviceType = detectDeviceType; - exports.difference = difference; - exports.differenceBy = differenceBy; - exports.differenceWith = differenceWith; - exports.dig = dig; - exports.digitize = digitize; - exports.distance = distance; - exports.drop = drop; - exports.dropRight = dropRight; - exports.dropRightWhile = dropRightWhile; - exports.dropWhile = dropWhile; - exports.elementContains = elementContains; - exports.elementIsVisibleInViewport = elementIsVisibleInViewport; - exports.elo = elo; - exports.equals = equals; - exports.escapeHTML = escapeHTML; - exports.escapeRegExp = escapeRegExp; - exports.everyNth = everyNth; - exports.extendHex = extendHex; - exports.factorial = factorial; - exports.fibonacci = fibonacci; - exports.filterNonUnique = filterNonUnique; - exports.filterNonUniqueBy = filterNonUniqueBy; - exports.findKey = findKey; - exports.findLast = findLast; - exports.findLastIndex = findLastIndex; - exports.findLastKey = findLastKey; - exports.flatten = flatten; - exports.flattenObject = flattenObject; - exports.flip = flip; - exports.forEachRight = forEachRight; - exports.forOwn = forOwn; - exports.forOwnRight = forOwnRight; - exports.formatDuration = formatDuration; - exports.fromCamelCase = fromCamelCase; - exports.functionName = functionName; - exports.functions = functions; - exports.gcd = gcd; - exports.geometricProgression = geometricProgression; - exports.get = get; - exports.getColonTimeFromDate = getColonTimeFromDate; - exports.getDaysDiffBetweenDates = getDaysDiffBetweenDates; - exports.getImages = getImages; - exports.getMeridiemSuffixOfInteger = getMeridiemSuffixOfInteger; - exports.getScrollPosition = getScrollPosition; - exports.getStyle = getStyle; - exports.getType = getType; - exports.getURLParameters = getURLParameters; - exports.groupBy = groupBy; - exports.hammingDistance = hammingDistance; - exports.hasClass = hasClass; - exports.hasFlags = hasFlags; - exports.hashBrowser = hashBrowser; - exports.hashNode = hashNode; - exports.head = head; - exports.hexToRGB = hexToRGB; - exports.hide = hide; - exports.httpGet = httpGet; - exports.httpPost = httpPost; - exports.httpsRedirect = httpsRedirect; - exports.hz = hz; - exports.inRange = inRange; - exports.indentString = indentString; - exports.indexOfAll = indexOfAll; - exports.initial = initial; - exports.initialize2DArray = initialize2DArray; - exports.initializeArrayWithRange = initializeArrayWithRange; - exports.initializeArrayWithRangeRight = initializeArrayWithRangeRight; - exports.initializeArrayWithValues = initializeArrayWithValues; - exports.initializeNDArray = initializeNDArray; - exports.insertAfter = insertAfter; - exports.insertBefore = insertBefore; - exports.intersection = intersection; - exports.intersectionBy = intersectionBy; - exports.intersectionWith = intersectionWith; - exports.invertKeyValues = invertKeyValues; - exports.is = is; - exports.isAbsoluteURL = isAbsoluteURL; - exports.isAfterDate = isAfterDate; - exports.isAnagram = isAnagram; - exports.isArrayLike = isArrayLike; - exports.isBeforeDate = isBeforeDate; - exports.isBoolean = isBoolean; - exports.isBrowser = isBrowser; - exports.isBrowserTabFocused = isBrowserTabFocused; - exports.isDivisible = isDivisible; - exports.isDuplexStream = isDuplexStream; - exports.isEmpty = isEmpty; - exports.isEven = isEven; - exports.isFunction = isFunction; - exports.isLowerCase = isLowerCase; - exports.isNil = isNil; - exports.isNull = isNull; - exports.isNumber = isNumber; - exports.isObject = isObject; - exports.isObjectLike = isObjectLike; - exports.isPlainObject = isPlainObject; - exports.isPrime = isPrime; - exports.isPrimitive = isPrimitive; - exports.isPromiseLike = isPromiseLike; - exports.isReadableStream = isReadableStream; - exports.isSameDate = isSameDate; - exports.isSorted = isSorted; - exports.isStream = isStream; - exports.isString = isString; - exports.isSymbol = isSymbol; - exports.isTravisCI = isTravisCI; - exports.isUndefined = isUndefined; - exports.isUpperCase = isUpperCase; - exports.isValidJSON = isValidJSON; - exports.isWritableStream = isWritableStream; - exports.join = join; - exports.last = last; - exports.lcm = lcm; - exports.longestItem = longestItem; - exports.lowercaseKeys = lowercaseKeys; - exports.luhnCheck = luhnCheck; - exports.mapKeys = mapKeys; - exports.mapObject = mapObject; - exports.mapString = mapString; - exports.mapValues = mapValues; - exports.mask = mask; - exports.matches = matches; - exports.matchesWith = matchesWith; - exports.maxBy = maxBy; - exports.maxDate = maxDate; - exports.maxN = maxN; - exports.median = median; - exports.memoize = memoize; - exports.merge = merge; - exports.minBy = minBy; - exports.minDate = minDate; - exports.minN = minN; - exports.mostPerformant = mostPerformant; - exports.negate = negate; - exports.nest = nest; - exports.nodeListToArray = nodeListToArray; - exports.none = none; - exports.nthArg = nthArg; - exports.nthElement = nthElement; - exports.objectFromPairs = objectFromPairs; - exports.objectToPairs = objectToPairs; - exports.observeMutations = observeMutations; - exports.off = off; - exports.offset = offset; - exports.omit = omit; - exports.omitBy = omitBy; - exports.on = on; - exports.onUserInputChange = onUserInputChange; - exports.once = once; - exports.orderBy = orderBy; - exports.over = over; - exports.overArgs = overArgs; - exports.pad = pad; - exports.palindrome = palindrome; - exports.parseCookie = parseCookie; - exports.partial = partial; - exports.partialRight = partialRight; - exports.partition = partition; - exports.percentile = percentile; - exports.permutations = permutations; - exports.pick = pick; - exports.pickBy = pickBy; - exports.pipeAsyncFunctions = pipeAsyncFunctions; - exports.pipeFunctions = pipeFunctions; - exports.pluralize = pluralize; - exports.powerset = powerset; - exports.prefix = prefix; - exports.prettyBytes = prettyBytes; - exports.primes = primes; - exports.promisify = promisify; - exports.pull = pull; - exports.pullAtIndex = pullAtIndex; - exports.pullAtValue = pullAtValue; - exports.pullBy = pullBy; - exports.radsToDegrees = radsToDegrees; - exports.randomHexColorCode = randomHexColorCode; - exports.randomIntArrayInRange = randomIntArrayInRange; - exports.randomIntegerInRange = randomIntegerInRange; - exports.randomNumberInRange = randomNumberInRange; - exports.readFileLines = readFileLines; - exports.rearg = rearg; - exports.recordAnimationFrames = recordAnimationFrames; - exports.redirect = redirect; - exports.reduceSuccessive = reduceSuccessive; - exports.reduceWhich = reduceWhich; - exports.reducedFilter = reducedFilter; - exports.reject = reject; - exports.remove = remove; - exports.removeNonASCII = removeNonASCII; - exports.renameKeys = renameKeys; - exports.reverseString = reverseString; - exports.round = round; - exports.runAsync = runAsync; - exports.runPromisesInSeries = runPromisesInSeries; - exports.sample = sample; - exports.sampleSize = sampleSize; - exports.scrollToTop = scrollToTop; - exports.sdbm = sdbm; - exports.serializeCookie = serializeCookie; - exports.setStyle = setStyle; - exports.shallowClone = shallowClone; - exports.shank = shank; - exports.show = show; - exports.shuffle = shuffle; - exports.similarity = similarity; - exports.size = size; - exports.sleep = sleep; - exports.smoothScroll = smoothScroll; - exports.sortCharactersInString = sortCharactersInString; - exports.sortedIndex = sortedIndex; - exports.sortedIndexBy = sortedIndexBy; - exports.sortedLastIndex = sortedLastIndex; - exports.sortedLastIndexBy = sortedLastIndexBy; - exports.splitLines = splitLines; - exports.spreadOver = spreadOver; - exports.stableSort = stableSort; - exports.standardDeviation = standardDeviation; - exports.stringPermutations = stringPermutations; - exports.stripHTMLTags = stripHTMLTags; - exports.sum = sum; - exports.sumBy = sumBy; - exports.sumPower = sumPower; - exports.symmetricDifference = symmetricDifference; - exports.symmetricDifferenceBy = symmetricDifferenceBy; - exports.symmetricDifferenceWith = symmetricDifferenceWith; - exports.tail = tail; - exports.take = take; - exports.takeRight = takeRight; - exports.takeRightWhile = takeRightWhile; - exports.takeWhile = takeWhile; - exports.throttle = throttle; - exports.timeTaken = timeTaken; - exports.times = times; - exports.toCamelCase = toCamelCase; - exports.toCurrency = toCurrency; - exports.toDecimalMark = toDecimalMark; - exports.toHash = toHash; - exports.toKebabCase = toKebabCase; - exports.toOrdinalSuffix = toOrdinalSuffix; - exports.toSafeInteger = toSafeInteger; - exports.toSnakeCase = toSnakeCase; - exports.toggleClass = toggleClass; - exports.tomorrow = tomorrow; - exports.transform = transform; - exports.triggerEvent = triggerEvent; - exports.truncateString = truncateString; - exports.truthCheckCollection = truthCheckCollection; - exports.unary = unary; - exports.uncurry = uncurry; - exports.unescapeHTML = unescapeHTML; - exports.unflattenObject = unflattenObject; - exports.unfold = unfold; - exports.union = union; - exports.unionBy = unionBy; - exports.unionWith = unionWith; - exports.uniqueElements = uniqueElements; - exports.uniqueElementsBy = uniqueElementsBy; - exports.uniqueElementsByRight = uniqueElementsByRight; - exports.uniqueSymmetricDifference = uniqueSymmetricDifference; - exports.untildify = untildify; - exports.unzip = unzip; - exports.unzipWith = unzipWith; - exports.validateNumber = validateNumber; - exports.when = when; - exports.without = without; - exports.words = words; - exports.xProd = xProd; - exports.yesNo = yesNo; - exports.zip = zip; - exports.zipObject = zipObject; - exports.zipWith = zipWith; - - Object.defineProperty(exports, '__esModule', { value: true }); + module.exports = {all,allEqual,any,approximatelyEqual,arrayToCSV,arrayToHtmlList,ary,atob,attempt,average,averageBy,bifurcate,bifurcateBy,bind,bindAll,bindKey,binomialCoefficient,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,composeRight,converge,copyToClipboard,countBy,counter,countOccurrences,createElement,createEventHub,CSVToArray,CSVToJSON,currentURL,curry,dayOfYear,debounce,decapitalize,deepClone,deepFlatten,deepFreeze,defaults,defer,degreesToRads,delay,detectDeviceType,difference,differenceBy,differenceWith,dig,digitize,distance,drop,dropRight,dropRightWhile,dropWhile,elementContains,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,filterNonUniqueBy,findKey,findLast,findLastIndex,findLastKey,flatten,flattenObject,flip,forEachRight,formatDuration,forOwn,forOwnRight,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getColonTimeFromDate,getDaysDiffBetweenDates,getImages,getMeridiemSuffixOfInteger,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,hz,indentString,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,initializeNDArray,inRange,insertAfter,insertBefore,intersection,intersectionBy,intersectionWith,invertKeyValues,is,isAbsoluteURL,isAfterDate,isAnagram,isArrayLike,isBeforeDate,isBoolean,isBrowser,isBrowserTabFocused,isDivisible,isDuplexStream,isEmpty,isEven,isFunction,isLowerCase,isNil,isNull,isNumber,isObject,isObjectLike,isPlainObject,isPrime,isPrimitive,isPromiseLike,isReadableStream,isSameDate,isSorted,isStream,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,isWritableStream,join,JSONtoCSV,JSONToFile,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapString,mapValues,mask,matches,matchesWith,maxBy,maxDate,maxN,median,memoize,merge,minBy,minDate,minN,mostPerformant,negate,nest,nodeListToArray,none,nthArg,nthElement,objectFromPairs,objectToPairs,observeMutations,off,offset,omit,omitBy,on,once,onUserInputChange,orderBy,over,overArgs,pad,palindrome,parseCookie,partial,partialRight,partition,percentile,permutations,pick,pickBy,pipeAsyncFunctions,pipeFunctions,pluralize,powerset,prefix,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,radsToDegrees,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,rearg,recordAnimationFrames,redirect,reducedFilter,reduceSuccessive,reduceWhich,reject,remove,removeNonASCII,renameKeys,reverseString,RGBToHex,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,serializeCookie,setStyle,shallowClone,shank,show,shuffle,similarity,size,sleep,smoothScroll,sortCharactersInString,sortedIndex,sortedIndexBy,sortedLastIndex,sortedLastIndexBy,splitLines,spreadOver,stableSort,standardDeviation,stringPermutations,stripHTMLTags,sum,sumBy,sumPower,symmetricDifference,symmetricDifferenceBy,symmetricDifferenceWith,tail,take,takeRight,takeRightWhile,takeWhile,throttle,times,timeTaken,toCamelCase,toCurrency,toDecimalMark,toggleClass,toHash,toKebabCase,tomorrow,toOrdinalSuffix,toSafeInteger,toSnakeCase,transform,triggerEvent,truncateString,truthCheckCollection,unary,uncurry,unescapeHTML,unflattenObject,unfold,union,unionBy,unionWith,uniqueElements,uniqueElementsBy,uniqueElementsByRight,uniqueSymmetricDifference,untildify,unzip,unzipWith,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,validateNumber,when,without,words,xProd,yesNo,zip,zipObject,zipWith}; }))); diff --git a/package-lock.json b/package-lock.json index 9d1988e75..7bcccf607 100644 --- a/package-lock.json +++ b/package-lock.json @@ -933,23 +933,6 @@ "acorn": "5.5.3" } }, - "acorn-jsx": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-3.0.1.tgz", - "integrity": "sha1-r9+UiPsezvyDSPb7IvRk4ypYs2s=", - "dev": true, - "requires": { - "acorn": "3.3.0" - }, - "dependencies": { - "acorn": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/acorn/-/acorn-3.3.0.tgz", - "integrity": "sha1-ReN/s56No/JbruP/U2niu18iAXo=", - "dev": true - } - } - }, "ajv": { "version": "5.5.2", "resolved": "https://registry.npmjs.org/ajv/-/ajv-5.5.2.tgz", @@ -962,12 +945,6 @@ "json-schema-traverse": "0.3.1" } }, - "ajv-keywords": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ajv-keywords/-/ajv-keywords-2.1.1.tgz", - "integrity": "sha1-YXmX/F9gV2iUxDX5QNgZ4TW4B2I=", - "dev": true - }, "amdefine": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/amdefine/-/amdefine-1.0.1.tgz", @@ -1357,16 +1334,6 @@ "integrity": "sha1-3wEKoSh+Fku9pvlyOwqWoexBh6E=", "dev": true }, - "array-includes": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.0.3.tgz", - "integrity": "sha1-GEtI9i2S10UrsxsyMWXH+L0CJm0=", - "dev": true, - "requires": { - "define-properties": "1.1.2", - "es-abstract": "1.11.0" - } - }, "array-union": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/array-union/-/array-union-1.0.2.tgz", @@ -1394,12 +1361,6 @@ "integrity": "sha1-iYUI2iIm84DfkEcoRWhJwVAaSw0=", "dev": true }, - "asap": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz", - "integrity": "sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY=", - "dev": true - }, "asn1": { "version": "0.2.4", "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.4.tgz", @@ -2291,12 +2252,6 @@ } } }, - "chardet": { - "version": "0.4.2", - "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.4.2.tgz", - "integrity": "sha1-tUc7M9yXxCTl2Y3IfVXU2KKci/I=", - "dev": true - }, "ci-info": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-1.5.1.tgz", @@ -2457,30 +2412,12 @@ "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "dev": true }, - "concat-stream": { - "version": "1.6.2", - "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", - "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", - "dev": true, - "requires": { - "buffer-from": "1.1.0", - "inherits": "2.0.3", - "readable-stream": "2.3.3", - "typedarray": "0.0.6" - } - }, "console-control-strings": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", "integrity": "sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4=", "dev": true }, - "contains-path": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/contains-path/-/contains-path-0.1.0.tgz", - "integrity": "sha1-/ozxhP9mcLa67wGp1IYaXL7EEgo=", - "dev": true - }, "convert-source-map": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-1.5.1.tgz", @@ -2605,12 +2542,6 @@ "ms": "2.0.0" } }, - "debug-log": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/debug-log/-/debug-log-1.0.1.tgz", - "integrity": "sha1-IwdjLUwEOCuN+KMvcLiVBG1SdF8=", - "dev": true - }, "decamelize": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", @@ -2712,20 +2643,6 @@ } } }, - "deglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/deglob/-/deglob-2.1.1.tgz", - "integrity": "sha512-2kjwuGGonL7gWE1XU4Fv79+vVzpoQCl0V+boMwWtOQJV2AGDabCwez++nB1Nli/8BabAfZQ/UuHPlp6AymKdWw==", - "dev": true, - "requires": { - "find-root": "1.1.0", - "glob": "7.1.2", - "ignore": "3.3.8", - "pkg-config": "1.1.1", - "run-parallel": "1.1.9", - "uniq": "1.0.1" - } - }, "del": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/del/-/del-2.2.2.tgz", @@ -2822,15 +2739,6 @@ "integrity": "sha512-h3zEBLdHvsKfaXv1SHAtykJyNtwYFEKkrWGSFyW1BzGgPQ4ykAzD5Hd8C5MZGTAEhkCKmtyIwYUrapsI0xfKww==", "dev": true }, - "encoding": { - "version": "0.1.12", - "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.12.tgz", - "integrity": "sha1-U4tm8+5izRq1HsMjgp0flIDHS+s=", - "dev": true, - "requires": { - "iconv-lite": "0.4.19" - } - }, "entities": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/entities/-/entities-1.1.1.tgz", @@ -3116,97 +3024,6 @@ } } }, - "eslint-config-semistandard": { - "version": "12.0.1", - "resolved": "https://registry.npmjs.org/eslint-config-semistandard/-/eslint-config-semistandard-12.0.1.tgz", - "integrity": "sha512-4zaPW5uRFasf2uRZkE19Y+W84KBV3q+oyWYOsgUN+5DQXE5HCsh7ZxeWDXxozk7NPycGm0kXcsJzLe5GZ1jCeg==", - "dev": true - }, - "eslint-config-standard-jsx": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/eslint-config-standard-jsx/-/eslint-config-standard-jsx-5.0.0.tgz", - "integrity": "sha512-rLToPAEqLMPBfWnYTu6xRhm2OWziS2n40QFqJ8jAM8NSVzeVKTa3nclhsU4DpPJQRY60F34Oo1wi/71PN/eITg==", - "dev": true - }, - "eslint-import-resolver-node": { - "version": "0.3.2", - "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.2.tgz", - "integrity": "sha512-sfmTqJfPSizWu4aymbPr4Iidp5yKm8yDkHp+Ir3YiTHiiDfxh69mOUsmiqW6RZ9zRXFaF64GtYmN7e+8GHBv6Q==", - "dev": true, - "requires": { - "debug": "2.6.9", - "resolve": "1.5.0" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - } - } - }, - "eslint-module-utils": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.2.0.tgz", - "integrity": "sha1-snA2LNiLGkitMIl2zn+lTphBF0Y=", - "dev": true, - "requires": { - "debug": "2.6.9", - "pkg-dir": "1.0.0" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "pkg-dir": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-1.0.0.tgz", - "integrity": "sha1-ektQio1bstYp1EcFb/TpyTFM89Q=", - "dev": true, - "requires": { - "find-up": "1.1.2" - } - } - } - }, - "eslint-plugin-async-await": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-async-await/-/eslint-plugin-async-await-0.0.0.tgz", - "integrity": "sha1-DyrhejgUeAY11I8kCd+eN4mMoJ8=", - "dev": true - }, - "eslint-plugin-react": { - "version": "7.6.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.6.1.tgz", - "integrity": "sha512-30aMOHWX/DOaaLJVBHz6RMvYM2qy5GH63+y2PLFdIrYe4YLtODFmT3N1YA7ZqUnaBweVbedr4K4cqxOlWAPjIw==", - "dev": true, - "requires": { - "doctrine": "2.1.0", - "has": "1.0.1", - "jsx-ast-utils": "2.0.1", - "prop-types": "15.6.1" - } - }, - "eslint-scope": { - "version": "3.7.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-3.7.1.tgz", - "integrity": "sha1-PWPD7f2gLgbgGkUq2IyqzHzctug=", - "dev": true, - "requires": { - "esrecurse": "4.2.1", - "estraverse": "4.2.0" - } - }, "eslint-utils": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.3.1.tgz", @@ -3219,16 +3036,6 @@ "integrity": "sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==", "dev": true }, - "espree": { - "version": "3.5.4", - "resolved": "https://registry.npmjs.org/espree/-/espree-3.5.4.tgz", - "integrity": "sha512-yAcIQxtmMiB/jL32dzEp2enBeidsB7xWPLNiw3IIkpVds1P+h7qF9YwJq1yUNzp2OKXgAprs4F61ih66UsoD1A==", - "dev": true, - "requires": { - "acorn": "5.5.3", - "acorn-jsx": "3.0.1" - } - }, "esprima": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.0.tgz", @@ -3360,17 +3167,6 @@ } } }, - "external-editor": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/external-editor/-/external-editor-2.2.0.tgz", - "integrity": "sha512-bSn6gvGxKt+b7+6TKEv1ZycHleA7aHhRHyAqJyp5pbUFuYYNIzpZnQDk7AsYckyWdEnTeAnay0aCy2aV6iTk9A==", - "dev": true, - "requires": { - "chardet": "0.4.2", - "iconv-lite": "0.4.19", - "tmp": "0.0.33" - } - }, "extglob": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/extglob/-/extglob-0.3.2.tgz", @@ -3413,29 +3209,6 @@ "bser": "2.0.0" } }, - "fbjs": { - "version": "0.8.17", - "resolved": "https://registry.npmjs.org/fbjs/-/fbjs-0.8.17.tgz", - "integrity": "sha1-xNWY6taUkRJlPWWIsBpc3Nn5D90=", - "dev": true, - "requires": { - "core-js": "1.2.7", - "isomorphic-fetch": "2.2.1", - "loose-envify": "1.3.1", - "object-assign": "4.1.1", - "promise": "7.3.1", - "setimmediate": "1.0.5", - "ua-parser-js": "0.7.18" - }, - "dependencies": { - "core-js": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-1.2.7.tgz", - "integrity": "sha1-ZSKUwUZR2yj6k70tX/KYOk8IxjY=", - "dev": true - } - } - }, "figures": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", @@ -3484,12 +3257,6 @@ "repeat-string": "1.6.1" } }, - "find-root": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/find-root/-/find-root-1.1.0.tgz", - "integrity": "sha512-NKfW6bec6GfKc0SGx1e07QZY9PE99u0Bft/0rzSD5k3sO/vwkVUpDUKVm5Gpp5Ue3YfShPFTX2070tDs5kB9Ng==", - "dev": true - }, "find-up": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/find-up/-/find-up-1.1.2.tgz", @@ -4661,18 +4428,6 @@ } } }, - "iconv-lite": { - "version": "0.4.19", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.19.tgz", - "integrity": "sha512-oTZqweIP51xaGPI4uPa56/Pri/480R+mo7SeU+YETByQNhDG55ycFyNLIgta9vXhILrxXDmF7ZGhqZIcuN0gJQ==", - "dev": true - }, - "ignore": { - "version": "3.3.8", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-3.3.8.tgz", - "integrity": "sha512-pUh+xUQQhQzevjRHHFqqcTy0/dP/kS9I8HSrUydhihjuD09W6ldVWFtIrwhXdUJHis3i2rZNqEHpZH/cbinFbg==", - "dev": true - }, "import-local": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/import-local/-/import-local-1.0.0.tgz", @@ -4720,54 +4475,6 @@ "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", "dev": true }, - "inquirer": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-3.3.0.tgz", - "integrity": "sha512-h+xtnyk4EwKvFWHrUYsWErEVR+igKtLdchu+o0Z1RL7VU/jVMFbYir2bp6bAj8efFNxWqHX0dIss6fJQ+/+qeQ==", - "dev": true, - "requires": { - "ansi-escapes": "3.1.0", - "chalk": "2.4.1", - "cli-cursor": "2.1.0", - "cli-width": "2.2.0", - "external-editor": "2.2.0", - "figures": "2.0.0", - "lodash": "4.17.11", - "mute-stream": "0.0.7", - "run-async": "2.3.0", - "rx-lite": "4.0.8", - "rx-lite-aggregates": "4.0.8", - "string-width": "2.1.1", - "strip-ansi": "4.0.0", - "through": "2.3.8" - }, - "dependencies": { - "ansi-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.0.tgz", - "integrity": "sha1-7QMXwyIGT3lGbAKWa922Bas32Zg=", - "dev": true - }, - "figures": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/figures/-/figures-2.0.0.tgz", - "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", - "dev": true, - "requires": { - "escape-string-regexp": "1.0.5" - } - }, - "strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", - "dev": true, - "requires": { - "ansi-regex": "3.0.0" - } - } - } - }, "invariant": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/invariant/-/invariant-2.2.2.tgz", @@ -5059,16 +4766,6 @@ "isarray": "1.0.0" } }, - "isomorphic-fetch": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/isomorphic-fetch/-/isomorphic-fetch-2.2.1.tgz", - "integrity": "sha1-YRrhrPFPXoH3KVB0coGf6XM1WKk=", - "dev": true, - "requires": { - "node-fetch": "1.7.3", - "whatwg-fetch": "2.0.4" - } - }, "isstream": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", @@ -5746,15 +5443,6 @@ "verror": "1.10.0" } }, - "jsx-ast-utils": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-2.0.1.tgz", - "integrity": "sha1-6AGxs5mF4g//yHtA43SAgOLcrH8=", - "dev": true, - "requires": { - "array-includes": "3.0.3" - } - }, "kind-of": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", @@ -5810,18 +5498,6 @@ "uc.micro": "1.0.5" } }, - "load-json-file": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-2.0.0.tgz", - "integrity": "sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg=", - "dev": true, - "requires": { - "graceful-fs": "4.1.11", - "parse-json": "2.2.0", - "pify": "2.3.0", - "strip-bom": "3.0.0" - } - }, "locate-path": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-2.0.0.tgz", @@ -5858,12 +5534,6 @@ "integrity": "sha1-4j8/nE+Pvd6HJSnBBxhXoIblzO8=", "dev": true }, - "lodash.cond": { - "version": "4.5.2", - "resolved": "https://registry.npmjs.org/lodash.cond/-/lodash.cond-4.5.2.tgz", - "integrity": "sha1-9HGh2khr5g9quVXRcRVSPdHSVdU=", - "dev": true - }, "lodash.isplainobject": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", @@ -6217,16 +5887,6 @@ "lower-case": "1.1.4" } }, - "node-fetch": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-1.7.3.tgz", - "integrity": "sha512-NhZ4CsKx7cYm2vSrBAr2PvFOe6sWDf0UYLRqA6svUYg7+/TSfVAu49jYC4BvQ4Sms9SZgdqGBgroqfDhJdTyKQ==", - "dev": true, - "requires": { - "encoding": "0.1.12", - "is-stream": "1.1.0" - } - }, "node-gyp": { "version": "3.8.0", "resolved": "https://registry.npmjs.org/node-gyp/-/node-gyp-3.8.0.tgz", @@ -6824,66 +6484,6 @@ "pinkie": "2.0.4" } }, - "pkg-conf": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/pkg-conf/-/pkg-conf-2.1.0.tgz", - "integrity": "sha1-ISZRTKbyq/69FoWW3xi6V4Z/AFg=", - "dev": true, - "requires": { - "find-up": "2.1.0", - "load-json-file": "4.0.0" - }, - "dependencies": { - "find-up": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", - "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", - "dev": true, - "requires": { - "locate-path": "2.0.0" - } - }, - "load-json-file": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-4.0.0.tgz", - "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", - "dev": true, - "requires": { - "graceful-fs": "4.1.11", - "parse-json": "4.0.0", - "pify": "3.0.0", - "strip-bom": "3.0.0" - } - }, - "parse-json": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-4.0.0.tgz", - "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", - "dev": true, - "requires": { - "error-ex": "1.3.1", - "json-parse-better-errors": "1.0.2" - } - }, - "pify": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pify/-/pify-3.0.0.tgz", - "integrity": "sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=", - "dev": true - } - } - }, - "pkg-config": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/pkg-config/-/pkg-config-1.1.1.tgz", - "integrity": "sha1-VX7yLXPaPIg3EHdmxS6tq94pj+Q=", - "dev": true, - "requires": { - "debug-log": "1.0.1", - "find-root": "1.1.0", - "xtend": "4.0.1" - } - }, "pkg-dir": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-2.0.0.tgz", @@ -6986,15 +6586,6 @@ "integrity": "sha1-ihvjZr+Pwj2yvSPxDG/pILQ4nR8=", "dev": true }, - "promise": { - "version": "7.3.1", - "resolved": "https://registry.npmjs.org/promise/-/promise-7.3.1.tgz", - "integrity": "sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg==", - "dev": true, - "requires": { - "asap": "2.0.6" - } - }, "prompts": { "version": "0.1.14", "resolved": "https://registry.npmjs.org/prompts/-/prompts-0.1.14.tgz", @@ -7005,17 +6596,6 @@ "sisteransi": "0.1.1" } }, - "prop-types": { - "version": "15.6.1", - "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.6.1.tgz", - "integrity": "sha512-4ec7bY1Y66LymSUOH/zARVYObB23AT2h8cf6e/O6ZALB/N0sqZFEx7rq6EYPX2MkOdKORuooI/H5k9TlR4q7kQ==", - "dev": true, - "requires": { - "fbjs": "0.8.17", - "loose-envify": "1.3.1", - "object-assign": "4.1.1" - } - }, "pseudomap": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", @@ -7437,27 +7017,6 @@ "integrity": "sha512-kc120TBlQ3mih1LSzdAJXo4xn/GWS2ec0l3S+syHDXP9uRr0JAT8Qd3mdMuyjqCzeZktgP3try92cEgf9Nks8A==", "dev": true }, - "run-parallel": { - "version": "1.1.9", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.1.9.tgz", - "integrity": "sha512-DEqnSRTDw/Tc3FXf49zedI638Z9onwUotBMiUFKmrO2sdFKIbXamXGQ3Axd4qgphxKB4kw/qP1w5kTxnfU1B9Q==", - "dev": true - }, - "rx-lite": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/rx-lite/-/rx-lite-4.0.8.tgz", - "integrity": "sha1-Cx4Rr4vESDbwSmQH6S2kJGe3lEQ=", - "dev": true - }, - "rx-lite-aggregates": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/rx-lite-aggregates/-/rx-lite-aggregates-4.0.8.tgz", - "integrity": "sha1-dTuHqJoRyVRnxKwWJsTvxOBcZ74=", - "dev": true, - "requires": { - "rx-lite": "4.0.8" - } - }, "rxjs": { "version": "6.3.3", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.3.3.tgz", @@ -7935,185 +7494,6 @@ "dev": true, "optional": true }, - "semistandard": { - "version": "12.0.1", - "resolved": "https://registry.npmjs.org/semistandard/-/semistandard-12.0.1.tgz", - "integrity": "sha512-+FBRXBCi8GC1Nivc4ruw2KXER31bE1lrNyESo7prn2Sv9I9+H/Iqpt0NOtlV/GUxq34AgJwJViBUpA3/PUGqOw==", - "dev": true, - "requires": { - "eslint": "4.18.2", - "eslint-config-semistandard": "12.0.1", - "eslint-config-standard": "11.0.0", - "eslint-config-standard-jsx": "5.0.0", - "eslint-plugin-import": "2.8.0", - "eslint-plugin-node": "6.0.1", - "eslint-plugin-promise": "3.6.0", - "eslint-plugin-react": "7.6.1", - "eslint-plugin-standard": "3.0.1", - "standard-engine": "8.0.1" - }, - "dependencies": { - "eslint": { - "version": "4.18.2", - "resolved": "http://registry.npmjs.org/eslint/-/eslint-4.18.2.tgz", - "integrity": "sha512-qy4i3wODqKMYfz9LUI8N2qYDkHkoieTbiHpMrYUI/WbjhXJQr7lI4VngixTgaG+yHX+NBCv7nW4hA0ShbvaNKw==", - "dev": true, - "requires": { - "ajv": "5.5.2", - "babel-code-frame": "6.26.0", - "chalk": "2.4.1", - "concat-stream": "1.6.2", - "cross-spawn": "5.1.0", - "debug": "3.1.0", - "doctrine": "2.1.0", - "eslint-scope": "3.7.1", - "eslint-visitor-keys": "1.0.0", - "espree": "3.5.4", - "esquery": "1.0.1", - "esutils": "2.0.2", - "file-entry-cache": "2.0.0", - "functional-red-black-tree": "1.0.1", - "glob": "7.1.2", - "globals": "11.8.0", - "ignore": "3.3.8", - "imurmurhash": "0.1.4", - "inquirer": "3.3.0", - "is-resolvable": "1.1.0", - "js-yaml": "3.12.0", - "json-stable-stringify-without-jsonify": "1.0.1", - "levn": "0.3.0", - "lodash": "4.17.11", - "minimatch": "3.0.4", - "mkdirp": "0.5.1", - "natural-compare": "1.4.0", - "optionator": "0.8.2", - "path-is-inside": "1.0.2", - "pluralize": "7.0.0", - "progress": "2.0.0", - "require-uncached": "1.0.3", - "semver": "5.4.1", - "strip-ansi": "4.0.0", - "strip-json-comments": "2.0.1", - "table": "4.0.2", - "text-table": "0.2.0" - } - }, - "eslint-config-standard": { - "version": "11.0.0", - "resolved": "http://registry.npmjs.org/eslint-config-standard/-/eslint-config-standard-11.0.0.tgz", - "integrity": "sha512-oDdENzpViEe5fwuRCWla7AXQd++/oyIp8zP+iP9jiUPG6NBj3SHgdgtl/kTn00AjeN+1HNvavTKmYbMo+xMOlw==", - "dev": true - }, - "eslint-plugin-import": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.8.0.tgz", - "integrity": "sha512-Rf7dfKJxZ16QuTgVv1OYNxkZcsu/hULFnC+e+w0Gzi6jMC3guQoWQgxYxc54IDRinlb6/0v5z/PxxIKmVctN+g==", - "dev": true, - "requires": { - "builtin-modules": "1.1.1", - "contains-path": "0.1.0", - "debug": "2.6.9", - "doctrine": "1.5.0", - "eslint-import-resolver-node": "0.3.2", - "eslint-module-utils": "2.2.0", - "has": "1.0.1", - "lodash.cond": "4.5.2", - "minimatch": "3.0.4", - "read-pkg-up": "2.0.0" - }, - "dependencies": { - "debug": { - "version": "2.6.9", - "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", - "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", - "dev": true, - "requires": { - "ms": "2.0.0" - } - }, - "doctrine": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-1.5.0.tgz", - "integrity": "sha1-N53Ocw9hZvds76TmcHoVmwLFpvo=", - "dev": true, - "requires": { - "esutils": "2.0.2", - "isarray": "1.0.0" - } - } - } - }, - "eslint-plugin-node": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-node/-/eslint-plugin-node-6.0.1.tgz", - "integrity": "sha512-Q/Cc2sW1OAISDS+Ji6lZS2KV4b7ueA/WydVWd1BECTQwVvfQy5JAi3glhINoKzoMnfnuRgNP+ZWKrGAbp3QDxw==", - "dev": true, - "requires": { - "ignore": "3.3.8", - "minimatch": "3.0.4", - "resolve": "1.5.0", - "semver": "5.4.1" - } - }, - "eslint-plugin-promise": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-promise/-/eslint-plugin-promise-3.6.0.tgz", - "integrity": "sha512-YQzM6TLTlApAr7Li8vWKR+K3WghjwKcYzY0d2roWap4SLK+kzuagJX/leTetIDWsFcTFnKNJXWupDCD6aZkP2Q==", - "dev": true - }, - "eslint-plugin-standard": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/eslint-plugin-standard/-/eslint-plugin-standard-3.0.1.tgz", - "integrity": "sha1-NNDJFbRe3G8BA5PH7vOCOwhWXPI=", - "dev": true - }, - "find-up": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-2.1.0.tgz", - "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", - "dev": true, - "requires": { - "locate-path": "2.0.0" - } - }, - "globals": { - "version": "11.8.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.8.0.tgz", - "integrity": "sha512-io6LkyPVuzCHBSQV9fmOwxZkUk6nIaGmxheLDgmuFv89j0fm2aqDbIXKAGfzCMHqz3HLF2Zf8WSG6VqMh2qFmA==", - "dev": true - }, - "path-type": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-2.0.0.tgz", - "integrity": "sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM=", - "dev": true, - "requires": { - "pify": "2.3.0" - } - }, - "read-pkg": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-2.0.0.tgz", - "integrity": "sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg=", - "dev": true, - "requires": { - "load-json-file": "2.0.0", - "normalize-package-data": "2.4.0", - "path-type": "2.0.0" - } - }, - "read-pkg-up": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/read-pkg-up/-/read-pkg-up-2.0.0.tgz", - "integrity": "sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4=", - "dev": true, - "requires": { - "find-up": "2.1.0", - "read-pkg": "2.0.0" - } - } - } - }, "semver": { "version": "5.4.1", "resolved": "https://registry.npmjs.org/semver/-/semver-5.4.1.tgz", @@ -8155,12 +7535,6 @@ } } }, - "setimmediate": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", - "integrity": "sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU=", - "dev": true - }, "shebang-command": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz", @@ -8430,18 +7804,6 @@ "integrity": "sha1-1PM6tU6OOHeLDKXP07OvsS22hiA=", "dev": true }, - "standard-engine": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/standard-engine/-/standard-engine-8.0.1.tgz", - "integrity": "sha512-LA531C3+nljom/XRvdW/hGPXwmilRkaRkENhO3FAGF1Vtq/WtCXzgmnc5S6vUHHsgv534MRy02C1ikMwZXC+tw==", - "dev": true, - "requires": { - "deglob": "2.1.1", - "get-stdin": "6.0.0", - "minimist": "1.2.0", - "pkg-conf": "2.1.0" - } - }, "static-extend": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/static-extend/-/static-extend-0.1.2.tgz", @@ -8613,20 +7975,6 @@ "integrity": "sha1-rifbOPZgp64uHDt9G8KQgZuFGeY=", "dev": true }, - "table": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/table/-/table-4.0.2.tgz", - "integrity": "sha512-UUkEAPdSGxtRpiV9ozJ5cMTtYiqz7Ni1OGqLXRCynrvzdtR1p+cfOWe2RJLwvUG8hNanaSRjecIqwOjqeatDsA==", - "dev": true, - "requires": { - "ajv": "5.5.2", - "ajv-keywords": "2.1.1", - "chalk": "2.4.1", - "lodash": "4.17.11", - "slice-ansi": "1.0.0", - "string-width": "2.1.1" - } - }, "tar": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/tar/-/tar-2.2.1.tgz", @@ -8818,18 +8166,6 @@ "prelude-ls": "1.1.2" } }, - "typedarray": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", - "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=", - "dev": true - }, - "ua-parser-js": { - "version": "0.7.18", - "resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.18.tgz", - "integrity": "sha512-LtzwHlVHwFGTptfNSgezHp7WUlwiqb0gA9AALRbKaERfxwJoiX0A73QbTToxteIAuIaFshhgIZfqK8s7clqgnA==", - "dev": true - }, "uc.micro": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-1.0.5.tgz", @@ -8917,12 +8253,6 @@ } } }, - "uniq": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/uniq/-/uniq-1.0.1.tgz", - "integrity": "sha1-sxxa6CVIRKOoKBVBzisEuGWnNP8=", - "dev": true - }, "universalify": { "version": "0.1.1", "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.1.tgz", @@ -9111,12 +8441,6 @@ } } }, - "whatwg-fetch": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-2.0.4.tgz", - "integrity": "sha512-dcQ1GWpOD/eEQ97k66aiEVpNnapVj90/+R+SXTPYGHpYBBypfKJEQjLrvMZ7YXbKm21gXd4NcuxUTjiv1YtLng==", - "dev": true - }, "whatwg-mimetype": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-2.1.0.tgz", @@ -9252,12 +8576,6 @@ "integrity": "sha512-A5CUptxDsvxKJEU3yO6DuWBSJz/qizqzJKOMIfUJHETbBw/sFaDxgd6fxm1ewUaM0jZ444Fc5vC5ROYurg/4Pw==", "dev": true }, - "xtend": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz", - "integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68=", - "dev": true - }, "y18n": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz", diff --git a/scripts/module.js b/scripts/module.js index e13e71001..901778a05 100644 --- a/scripts/module.js +++ b/scripts/module.js @@ -59,7 +59,7 @@ const codeRE = /```\s*js([\s\S]*?)```/; fs.writeFileSync(TEST_PACKAGE, `${requires}\n\n${importData}\n\n${testExports}`); // Check Travis builds - Will skip builds on Travis if not CRON/API - if (!util.isTravisCI() && util.isNotTravisCronOrAPI()) { + if (util.isTravisCI() && util.isNotTravisCronOrAPI()) { fs.unlink(IMPORTS); console.log( `${chalk.green('NOBUILD')} Module build terminated, not a cron job or a custom build!` diff --git a/test/_30s.js b/test/_30s.js index f27af434f..0da3161e4 100644 --- a/test/_30s.js +++ b/test/_30s.js @@ -1,36 +1,36 @@ const crypto = typeof require !== "undefined" && require('crypto'); const fs = typeof require !== "undefined" && require('fs'); -const all = (arr, fn = Boolean) => arr.every(fn); -const allEqual = arr => arr.every(val => val === arr[0]); -const any = (arr, fn = Boolean) => arr.some(fn); -const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon; -const arrayToCSV = (arr, delimiter = ',') => + const all = (arr, fn = Boolean) => arr.every(fn); + const allEqual = arr => arr.every(val => val === arr[0]); + const any = (arr, fn = Boolean) => arr.some(fn); + const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon; + const arrayToCSV = (arr, delimiter = ',') => arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n'); -const arrayToHtmlList = (arr, listID) => + const arrayToHtmlList = (arr, listID) => (el => ( (el = document.querySelector('#' + listID)), (el.innerHTML += arr.map(item => `
  • ${item}
  • `).join('')) ))(); -const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); + const ary = (fn, n) => (...args) => fn(...args.slice(0, n)); const atob = str => Buffer.from(str, 'base64').toString('binary'); -const attempt = (fn, ...args) => { + const attempt = (fn, ...args) => { try { return fn(...args); } catch (e) { return e instanceof Error ? e : new Error(e); } }; -const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length; -const averageBy = (arr, fn) => + const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length; + const averageBy = (arr, fn) => arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) / arr.length; -const bifurcate = (arr, filter) => + const bifurcate = (arr, filter) => arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]); -const bifurcateBy = (arr, fn) => + const bifurcateBy = (arr, fn) => arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]); -const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]); -const bindAll = (obj, ...fns) => + const bind = (fn, context, ...boundArgs) => (...args) => fn.apply(context, [...boundArgs, ...args]); + const bindAll = (obj, ...fns) => fns.forEach( fn => ( (f = obj[fn]), @@ -39,9 +39,9 @@ const bindAll = (obj, ...fns) => }) ) ); -const bindKey = (context, fn, ...boundArgs) => (...args) => + const bindKey = (context, fn, ...boundArgs) => (...args) => context[fn].apply(context, [...boundArgs, ...args]); -const binomialCoefficient = (n, k) => { + const binomialCoefficient = (n, k) => { if (Number.isNaN(n) || Number.isNaN(k)) return NaN; if (k < 0 || k > n) return 0; if (k === 0 || k === n) return 1; @@ -51,31 +51,31 @@ const binomialCoefficient = (n, k) => { for (let j = 2; j <= k; j++) res *= (n - j + 1) / j; return Math.round(res); }; -const bottomVisible = () => + const bottomVisible = () => document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight); const btoa = str => Buffer.from(str, 'binary').toString('base64'); -const byteSize = str => new Blob([str]).size; + const byteSize = str => new Blob([str]).size; const call = (key, ...args) => context => context[key](...args); -const capitalize = ([first, ...rest], lowerRest = false) => + const capitalize = ([first, ...rest], lowerRest = false) => first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); -const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); -const castArray = val => (Array.isArray(val) ? val : [val]); -const chainAsync = fns => { + const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); + const castArray = val => (Array.isArray(val) ? val : [val]); + const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); }; -const chunk = (arr, size) => + const chunk = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => arr.slice(i * size, i * size + size) ); -const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); -const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags); -const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); -const coalesceFactory = valid => (...args) => args.find(valid); + const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); + const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags); + const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); + const coalesceFactory = valid => (...args) => args.find(valid); const collectInto = fn => (...args) => fn(args); -const colorize = (...args) => ({ + const colorize = (...args) => ({ black: `\x1b[30m${args.join(' ')}`, red: `\x1b[31m${args.join(' ')}`, green: `\x1b[32m${args.join(' ')}`, @@ -93,11 +93,11 @@ const colorize = (...args) => ({ bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`, bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m` }); -const compact = arr => arr.filter(Boolean); -const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); -const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); -const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args))); -const copyToClipboard = str => { + const compact = arr => arr.filter(Boolean); + const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); + const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); + const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args))); + const copyToClipboard = str => { const el = document.createElement('textarea'); el.value = str; el.setAttribute('readonly', ''); @@ -114,12 +114,12 @@ const copyToClipboard = str => { document.getSelection().addRange(selected); } }; -const countBy = (arr, fn) => - arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { + const countBy = (arr, fn) => + arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => { acc[val] = (acc[val] || 0) + 1; return acc; }, {}); -const counter = (selector, start, end, step = 1, duration = 2000) => { + const counter = (selector, start, end, step = 1, duration = 2000) => { let current = start, _step = (end - start) * step < 0 ? -step : step, timer = setInterval(() => { @@ -130,13 +130,13 @@ const counter = (selector, start, end, step = 1, duration = 2000) => { }, Math.abs(Math.floor(duration / (end - start)))); return timer; }; -const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); -const createElement = str => { + const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); + const createElement = str => { const el = document.createElement('div'); el.innerHTML = str; return el.firstElementChild; }; -const createEventHub = () => ({ + const createEventHub = () => ({ hub: Object.create(null), emit(event, data) { (this.hub[event] || []).forEach(handler => handler(data)); @@ -150,12 +150,12 @@ const createEventHub = () => ({ if (i > -1) this.hub[event].splice(i, 1); } }); -const CSVToArray = (data, delimiter = ',', omitFirstRow = false) => + const CSVToArray = (data, delimiter = ',', omitFirstRow = false) => data .slice(omitFirstRow ? data.indexOf('\n') + 1 : 0) .split('\n') .map(v => v.split(delimiter)); -const CSVToJSON = (data, delimiter = ',') => { + const CSVToJSON = (data, delimiter = ',') => { const titles = data.slice(0, data.indexOf('\n')).split(delimiter); return data .slice(data.indexOf('\n') + 1) @@ -165,71 +165,71 @@ const CSVToJSON = (data, delimiter = ',') => { return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {}); }); }; -const currentURL = () => window.location.href; -const curry = (fn, arity = fn.length, ...args) => + const currentURL = () => window.location.href; + const curry = (fn, arity = fn.length, ...args) => arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args); -const dayOfYear = date => + const dayOfYear = date => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); -const debounce = (fn, ms = 0) => { + const debounce = (fn, ms = 0) => { let timeoutId; return function(...args) { clearTimeout(timeoutId); timeoutId = setTimeout(() => fn.apply(this, args), ms); }; }; -const decapitalize = ([first, ...rest], upperRest = false) => + const decapitalize = ([first, ...rest], upperRest = false) => first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join('')); -const deepClone = obj => { + const deepClone = obj => { let clone = Object.assign({}, obj); Object.keys(clone).forEach( key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key]) ); return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone; }; -const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); -const deepFreeze = obj => + const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); + const deepFreeze = obj => Object.keys(obj).forEach( prop => - !obj[prop] instanceof Object || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop]) + !(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop]) ) || Object.freeze(obj); -const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); -const defer = (fn, ...args) => setTimeout(fn, 1, ...args); -const degreesToRads = deg => (deg * Math.PI) / 180.0; -const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args); -const detectDeviceType = () => + const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj); + const defer = (fn, ...args) => setTimeout(fn, 1, ...args); + const degreesToRads = deg => (deg * Math.PI) / 180.0; + const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args); + const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop'; -const difference = (a, b) => { + const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }; -const differenceBy = (a, b, fn) => { - const s = new Set(b.map(v => fn(v))); + const differenceBy = (a, b, fn) => { + const s = new Set(b.map(fn)); return a.filter(x => !s.has(fn(x))); }; -const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1); -const dig = (obj, target) => + const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1); + const dig = (obj, target) => target in obj ? obj[target] : Object.values(obj).reduce((acc, val) => { - if (acc !== undefined) return acc; - if (typeof val === 'object') return dig(val, target); - }, undefined); -const digitize = n => [...`${n}`].map(i => parseInt(i)); -const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); -const drop = (arr, n = 1) => arr.slice(n); -const dropRight = (arr, n = 1) => arr.slice(0, -n); -const dropRightWhile = (arr, func) => { + if (acc !== undefined) return acc; + if (typeof val === 'object') return dig(val, target); + }, undefined); + const digitize = n => [...`${n}`].map(i => parseInt(i)); + const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); + const drop = (arr, n = 1) => arr.slice(n); + const dropRight = (arr, n = 1) => arr.slice(0, -n); + const dropRightWhile = (arr, func) => { while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1); return arr; }; -const dropWhile = (arr, func) => { + const dropWhile = (arr, func) => { while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); return arr; }; -const elementContains = (parent, child) => parent !== child && parent.contains(child); -const elementIsVisibleInViewport = (el, partiallyVisible = false) => { + const elementContains = (parent, child) => parent !== child && parent.contains(child); + const elementIsVisibleInViewport = (el, partiallyVisible = false) => { const { top, left, bottom, right } = el.getBoundingClientRect(); const { innerHeight, innerWidth } = window; return partiallyVisible @@ -237,14 +237,13 @@ const elementIsVisibleInViewport = (el, partiallyVisible = false) => { ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }; -const elo = ([...ratings], kFactor = 32, selfRating) => { + const elo = ([...ratings], kFactor = 32, selfRating) => { const [a, b] = ratings; const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400)); const newRating = (rating, i) => (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a)); - if (ratings.length === 2) { - return [newRating(a, 1), newRating(b, 0)]; - } + if (ratings.length === 2) return [newRating(a, 1), newRating(b, 0)]; + for (let i = 0, len = ratings.length; i < len; i++) { let j = i; while (j < len - 1) { @@ -254,7 +253,7 @@ const elo = ([...ratings], kFactor = 32, selfRating) => { } return ratings; }; -const equals = (a, b) => { + const equals = (a, b) => { if (a === b) return true; if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime(); if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b; @@ -264,7 +263,7 @@ const equals = (a, b) => { if (keys.length !== Object.keys(b).length) return false; return keys.every(k => equals(a[k], b[k])); }; -const escapeHTML = str => + const escapeHTML = str => str.replace( /[&<>'"]/g, tag => @@ -276,45 +275,45 @@ const escapeHTML = str => '"': '"' }[tag] || tag) ); -const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); -const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); -const extendHex = shortHex => + const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); + const extendHex = shortHex => '#' + shortHex .slice(shortHex.startsWith('#') ? 1 : 0) .split('') .map(x => x + x) .join(''); -const factorial = n => + const factorial = n => n < 0 ? (() => { - throw new TypeError('Negative numbers are not allowed!'); - })() + throw new TypeError('Negative numbers are not allowed!'); + })() : n <= 1 ? 1 : n * factorial(n - 1); -const fibonacci = n => + const fibonacci = n => Array.from({ length: n }).reduce( (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), [] ); -const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); -const filterNonUniqueBy = (arr, fn) => + const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); + const filterNonUniqueBy = (arr, fn) => arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j))); -const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj)); -const findLast = (arr, fn) => arr.filter(fn).pop(); -const findLastIndex = (arr, fn) => + const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj)); + const findLast = (arr, fn) => arr.filter(fn).pop(); + const findLastIndex = (arr, fn) => arr .map((val, i) => [i, val]) .filter(([i, val]) => fn(val, i, arr)) .pop()[0]; -const findLastKey = (obj, fn) => + const findLastKey = (obj, fn) => Object.keys(obj) .reverse() .find(key => fn(obj[key], key, obj)); -const flatten = (arr, depth = 1) => + const flatten = (arr, depth = 1) => arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []); -const flattenObject = (obj, prefix = '') => + const flattenObject = (obj, prefix = '') => Object.keys(obj).reduce((acc, k) => { const pre = prefix.length ? prefix + '.' : ''; if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k)); @@ -322,12 +321,12 @@ const flattenObject = (obj, prefix = '') => return acc; }, {}); const flip = fn => (first, ...rest) => fn(...rest, first); -const forEachRight = (arr, callback) => + const forEachRight = (arr, callback) => arr .slice(0) .reverse() .forEach(callback); -const formatDuration = ms => { + const formatDuration = ms => { if (ms < 0) ms = -ms; const time = { day: Math.floor(ms / 86400000), @@ -341,31 +340,31 @@ const formatDuration = ms => { .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`) .join(', '); }; -const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj)); -const forOwnRight = (obj, fn) => + const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj)); + const forOwnRight = (obj, fn) => Object.keys(obj) .reverse() .forEach(key => fn(obj[key], key, obj)); -const fromCamelCase = (str, separator = '_') => + const fromCamelCase = (str, separator = '_') => str .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2') .toLowerCase(); -const functionName = fn => (console.debug(fn.name), fn); -const functions = (obj, inherited = false) => + const functionName = fn => (console.debug(fn.name), fn); + const functions = (obj, inherited = false) => (inherited ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))] : Object.keys(obj) ).filter(key => typeof obj[key] === 'function'); -const gcd = (...arr) => { + const gcd = (...arr) => { const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); return [...arr].reduce((a, b) => _gcd(a, b)); }; -const geometricProgression = (end, start = 1, step = 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 ); -const get = (from, ...selectors) => + const get = (from, ...selectors) => [...selectors].map(s => s .replace(/\[([^\[\]]*)\]/g, '.$1.') @@ -373,14 +372,14 @@ const get = (from, ...selectors) => .filter(t => t !== '') .reduce((prev, cur) => prev && prev[cur], from) ); -const getColonTimeFromDate = date => date.toTimeString().slice(0, 8); -const getDaysDiffBetweenDates = (dateInitial, dateFinal) => + const getColonTimeFromDate = date => date.toTimeString().slice(0, 8); + const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); const getImages = (el, includeDuplicates = false) => { const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src')); return includeDuplicates ? images : [...new Set(images)]; }; -const getMeridiemSuffixOfInteger = num => + const getMeridiemSuffixOfInteger = num => num === 0 || num === 24 ? 12 + 'am' : num === 12 @@ -388,28 +387,28 @@ const getMeridiemSuffixOfInteger = num => : num < 12 ? (num % 12) + 'am' : (num % 12) + 'pm'; -const getScrollPosition = (el = window) => ({ + const getScrollPosition = (el = window) => ({ x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop }); -const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]; -const getType = v => + const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]; + const getType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase(); -const getURLParameters = url => + const getURLParameters = url => (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), {} ); -const groupBy = (arr, fn) => + const groupBy = (arr, fn) => arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {}); -const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length; -const hasClass = (el, className) => el.classList.contains(className); -const hasFlags = (...flags) => + const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length; + const hasClass = (el, className) => el.classList.contains(className); + const hasFlags = (...flags) => flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag)); -const hashBrowser = val => + const hashBrowser = val => crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => { let hexes = [], view = new DataView(h); @@ -417,7 +416,7 @@ const hashBrowser = val => hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8)); return hexes.join(''); }); - + const hashNode = val => new Promise(resolve => setTimeout( @@ -431,8 +430,8 @@ const hashNode = val => 0 ) ); -const head = arr => arr[0]; -const hexToRGB = hex => { + const head = arr => arr[0]; + const hexToRGB = hex => { let alpha = false, h = hex.slice(hex.startsWith('#') ? 1 : 0); if (h.length === 3) h = [...h].map(x => x + x).join(''); @@ -451,15 +450,15 @@ const hexToRGB = hex => { ')' ); }; -const hide = els => els.forEach(e => (e.style.display = 'none')); -const httpGet = (url, callback, err = console.error) => { + const hide = els => els.forEach(e => (e.style.display = 'none')); + const httpGet = (url, callback, err = console.error) => { const request = new XMLHttpRequest(); request.open('GET', url, true); request.onload = () => callback(request.responseText); request.onerror = () => err(request); request.send(); }; -const httpPost = (url, data, callback, err = console.error) => { + const httpPost = (url, data, callback, err = console.error) => { const request = new XMLHttpRequest(); request.open('POST', url, true); request.setRequestHeader('Content-type', 'application/json; charset=utf-8'); @@ -467,56 +466,56 @@ const httpPost = (url, data, callback, err = console.error) => { request.onerror = () => err(request); request.send(data); }; -const httpsRedirect = () => { + const httpsRedirect = () => { if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); }; -const hz = (fn, iterations = 100) => { + const hz = (fn, iterations = 100) => { const before = performance.now(); for (let i = 0; i < iterations; i++) fn(); return (1000 * iterations) / (performance.now() - before); }; -const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count)); -const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []); -const initial = arr => arr.slice(0, -1); -const initialize2DArray = (w, h, val = null) => + const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count)); + const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []); + const initial = arr => arr.slice(0, -1); + const initialize2DArray = (w, h, val = null) => Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val)); -const initializeArrayWithRange = (end, start = 0, step = 1) => + const initializeArrayWithRange = (end, start = 0, step = 1) => Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) => i * step + start); -const initializeArrayWithRangeRight = (end, start = 0, step = 1) => + const initializeArrayWithRangeRight = (end, start = 0, step = 1) => Array.from({ length: Math.ceil((end + 1 - start) / step) }).map( (v, i, arr) => (arr.length - i - 1) * step + start ); -const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); -const initializeNDArray = (val, ...args) => + const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); + const initializeNDArray = (val, ...args) => args.length === 0 ? val : Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1))); -const inRange = (n, start, end = null) => { + const inRange = (n, start, end = null) => { if (end && start > end) [end, start] = [start, end]; return end == null ? n >= 0 && n < start : n >= start && n < end; }; -const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString); -const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString); -const intersection = (a, b) => { + const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString); + const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString); + const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); }; -const intersectionBy = (a, b, fn) => { + const intersectionBy = (a, b, fn) => { const s = new Set(b.map(fn)); return a.filter(x => s.has(fn(x))); }; -const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1); -const invertKeyValues = (obj, fn) => + const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1); + const invertKeyValues = (obj, fn) => Object.keys(obj).reduce((acc, key) => { const val = fn ? fn(obj[key]) : obj[key]; acc[val] = acc[val] || []; acc[val].push(key); return acc; }, {}); -const is = (type, val) => ![, null].includes(val) && val.constructor === type; -const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); -const isAfterDate = (dateA, dateB) => dateA > dateB; -const isAnagram = (str1, str2) => { + const is = (type, val) => ![, null].includes(val) && val.constructor === type; + const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); + const isAfterDate = (dateA, dateB) => dateA > dateB; + const isAnagram = (str1, str2) => { const normalize = str => str .toLowerCase() @@ -526,12 +525,12 @@ const isAnagram = (str1, str2) => { .join(''); return normalize(str1) === normalize(str2); }; -const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function'; -const isBeforeDate = (dateA, dateB) => dateA < dateB; -const isBoolean = val => typeof val === 'boolean'; -const isBrowser = () => ![typeof window, typeof document].includes('undefined'); -const isBrowserTabFocused = () => !document.hidden; -const isDivisible = (dividend, divisor) => dividend % divisor === 0; + const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function'; + const isBeforeDate = (dateA, dateB) => dateA < dateB; + const isBoolean = val => typeof val === 'boolean'; + const isBrowser = () => ![typeof window, typeof document].includes('undefined'); + const isBrowserTabFocused = () => !document.hidden; + const isDivisible = (dividend, divisor) => dividend % divisor === 0; const isDuplexStream = val => val !== null && typeof val === 'object' && @@ -540,23 +539,23 @@ const isDivisible = (dividend, divisor) => dividend % divisor === 0; typeof val._readableState === 'object' && typeof val._write === 'function' && typeof val._writableState === 'object'; -const isEmpty = val => val == null || !(Object.keys(val) || val).length; -const isEven = num => num % 2 === 0; -const isFunction = val => typeof val === 'function'; -const isLowerCase = str => str === str.toLowerCase(); -const isNil = val => val === undefined || val === null; -const isNull = val => val === null; -const isNumber = val => typeof val === 'number'; -const isObject = obj => obj === Object(obj); -const isObjectLike = val => val !== null && typeof val === 'object'; -const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object; -const isPrime = num => { + const isEmpty = val => val == null || !(Object.keys(val) || val).length; + const isEven = num => num % 2 === 0; + const isFunction = val => typeof val === 'function'; + const isLowerCase = str => str === str.toLowerCase(); + const isNil = val => val === undefined || val === null; + const isNull = val => val === null; + const isNumber = val => typeof val === 'number'; + const isObject = obj => obj === Object(obj); + const isObjectLike = val => val !== null && typeof val === 'object'; + const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object; + 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 isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null; -const isPromiseLike = obj => + const isPrimitive = val => Object(val) !== val; + const isPromiseLike = obj => obj !== null && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'; @@ -566,8 +565,8 @@ const isPromiseLike = obj => typeof val.pipe === 'function' && typeof val._read === 'function' && typeof val._readableState === 'object'; -const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString(); -const isSorted = arr => { + const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString(); + const isSorted = arr => { let direction = -(arr[0] - arr[1]); for (let [i, val] of arr.entries()) { direction = !direction ? -(arr[i - 1] - arr[i]) : direction; @@ -577,11 +576,11 @@ const isSorted = arr => { }; const isStream = val => val !== null && typeof val === 'object' && typeof val.pipe === 'function'; const isString = val => typeof val === 'string'; -const isSymbol = val => typeof val === 'symbol'; -const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; -const isUndefined = val => val === undefined; -const isUpperCase = str => str === str.toUpperCase(); -const isValidJSON = obj => { + const isSymbol = val => typeof val === 'symbol'; + const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; + const isUndefined = val => val === undefined; + const isUpperCase = str => str === str.toUpperCase(); + const isValidJSON = obj => { try { JSON.parse(obj); return true; @@ -595,7 +594,7 @@ const isValidJSON = obj => { typeof val.pipe === 'function' && typeof val._write === 'function' && typeof val._writableState === 'object'; -const join = (arr, separator = ',', end = separator) => + const join = (arr, separator = ',', end = separator) => arr.reduce( (acc, val, i) => i === arr.length - 2 @@ -615,23 +614,23 @@ const join = (arr, separator = ',', end = separator) => ) ) ].join('\n'); - + const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); -const last = arr => arr[arr.length - 1]; -const lcm = (...arr) => { + const last = arr => arr[arr.length - 1]; + const lcm = (...arr) => { const gcd = (x, y) => (!y ? x : gcd(y, x % y)); const _lcm = (x, y) => (x * y) / gcd(x, y); return [...arr].reduce((a, b) => _lcm(a, b)); }; -const longestItem = (val, ...vals) => + const longestItem = (val, ...vals) => [val, ...vals].reduce((a, x) => (x.length > a.length ? x : a)); -const lowercaseKeys = obj => + const lowercaseKeys = obj => Object.keys(obj).reduce((acc, key) => { acc[key.toLowerCase()] = obj[key]; return acc; }, {}); -const luhnCheck = num => { + const luhnCheck = num => { let arr = (num + '') .split('') .reverse() @@ -641,44 +640,44 @@ const luhnCheck = num => { sum += lastDigit; return sum % 10 === 0; }; -const mapKeys = (obj, fn) => + const mapKeys = (obj, fn) => Object.keys(obj).reduce((acc, k) => { acc[fn(obj[k], k, obj)] = obj[k]; return acc; }, {}); -const mapObject = (arr, fn) => + const mapObject = (arr, fn) => (a => ( (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) ))(); -const mapString = (str, fn) => + const mapString = (str, fn) => str .split('') .map((c, i) => fn(c, i, str)) .join(''); -const mapValues = (obj, fn) => + const mapValues = (obj, fn) => Object.keys(obj).reduce((acc, k) => { acc[k] = fn(obj[k], k, obj); return acc; }, {}); -const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask); -const matches = (obj, source) => + const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask); + const matches = (obj, source) => Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]); -const matchesWith = (obj, source, fn) => + const matchesWith = (obj, source, fn) => Object.keys(source).every( key => obj.hasOwnProperty(key) && fn ? fn(obj[key], source[key], key, obj, source) : obj[key] == source[key] ); -const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); -const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates)); -const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); -const median = arr => { + const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); + const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates)); + const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); + const median = arr => { const mid = Math.floor(arr.length / 2), nums = [...arr].sort((a, b) => a - b); return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; }; -const memoize = fn => { + const memoize = fn => { const cache = new Map(); const cached = function(val) { return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val); @@ -686,7 +685,7 @@ const memoize = fn => { cached.cache = cache; return cached; }; -const merge = (...objs) => + const merge = (...objs) => [...objs].reduce( (acc, obj) => Object.keys(obj).reduce((a, k) => { @@ -695,10 +694,10 @@ const merge = (...objs) => }, {}), {} ); -const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); -const minDate = (...dates) => new Date(Math.min.apply(null, ...dates)); -const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); -const mostPerformant = (fns, iterations = 10000) => { + const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); + const minDate = (...dates) => new Date(Math.min.apply(null, ...dates)); + const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); + const mostPerformant = (fns, iterations = 10000) => { const times = fns.map(fn => { const before = performance.now(); for (let i = 0; i < iterations; i++) fn(); @@ -706,18 +705,18 @@ const mostPerformant = (fns, iterations = 10000) => { }); return times.indexOf(Math.min(...times)); }; -const negate = func => (...args) => !func(...args); -const nest = (items, id = null, link = 'parent_id') => + const negate = func => (...args) => !func(...args); + const nest = (items, id = null, link = 'parent_id') => items .filter(item => item[link] === id) .map(item => ({ ...item, children: nest(items, item.id) })); -const nodeListToArray = nodeList => [...nodeList]; -const none = (arr, fn = Boolean) => !arr.some(fn); -const nthArg = n => (...args) => args.slice(n)[0]; -const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0]; -const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {}); -const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); -const observeMutations = (element, callback, options) => { + const nodeListToArray = nodeList => [...nodeList]; + const none = (arr, fn = Boolean) => !arr.some(fn); + const nthArg = n => (...args) => args.slice(n)[0]; + const nthElement = (arr, n = 0) => (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0]; + const objectFromPairs = arr => arr.reduce((a, [key, val]) => ((a[key] = val), a), {}); + const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); + const observeMutations = (element, callback, options) => { const observer = new MutationObserver(mutations => mutations.forEach(m => callback(m))); observer.observe( element, @@ -735,22 +734,22 @@ const observeMutations = (element, callback, options) => { ); return observer; }; -const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); -const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)]; -const omit = (obj, arr) => + const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); + const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)]; + const omit = (obj, arr) => Object.keys(obj) .filter(k => !arr.includes(k)) .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); -const omitBy = (obj, fn) => + const omitBy = (obj, fn) => Object.keys(obj) .filter(k => !fn(obj[k], k)) .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); -const on = (el, evt, fn, opts = {}) => { + const on = (el, evt, fn, opts = {}) => { const delegatorFn = e => e.target.matches(opts.target) && fn.call(e.target, e); el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false); if (opts.target) return delegatorFn; }; -const once = fn => { + const once = fn => { let called = false; return function(...args) { if (called) return; @@ -758,7 +757,7 @@ const once = fn => { return fn.apply(this, args); }; }; -const onUserInputChange = callback => { + const onUserInputChange = callback => { let type = 'mouse', lastTime = 0; const mousemoveHandler = () => { @@ -772,7 +771,7 @@ const onUserInputChange = callback => { (type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler); }); }; -const orderBy = (arr, props, orders) => + const orderBy = (arr, props, orders) => [...arr].sort((a, b) => props.reduce((acc, prop, i) => { if (acc === 0) { @@ -782,15 +781,15 @@ const orderBy = (arr, props, orders) => return acc; }, 0) ); -const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); -const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val))); -const pad = (str, length, char = ' ') => + const over = (...fns) => (...args) => fns.map(fn => fn.apply(null, args)); + const overArgs = (fn, transforms) => (...args) => fn(...args.map((val, i) => transforms[i](val))); + const pad = (str, length, char = ' ') => str.padStart((str.length + length) / 2, char).padEnd(length, char); -const palindrome = str => { + const palindrome = str => { const s = str.toLowerCase().replace(/[\W_]/g, ''); return s === [...s].reverse().join(''); }; -const parseCookie = str => + const parseCookie = str => str .split(';') .map(v => v.split('=')) @@ -798,9 +797,9 @@ const parseCookie = str => acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim()); return acc; }, {}); -const partial = (fn, ...partials) => (...args) => fn(...partials, ...args); -const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials); -const partition = (arr, fn) => + const partial = (fn, ...partials) => (...args) => fn(...partials, ...args); + const partialRight = (fn, ...partials) => (...args) => fn(...args, ...partials); + const partition = (arr, fn) => arr.reduce( (acc, val, i, arr) => { acc[fn(val, i, arr) ? 0 : 1].push(val); @@ -808,9 +807,9 @@ const partition = (arr, fn) => }, [[], []] ); -const percentile = (arr, val) => + const percentile = (arr, val) => (100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0)) / arr.length; -const permutations = arr => { + const permutations = arr => { if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr; return arr.reduce( (acc, item, i) => @@ -820,22 +819,22 @@ const permutations = arr => { [] ); }; -const pick = (obj, arr) => + const pick = (obj, arr) => arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); -const pickBy = (obj, fn) => + const pickBy = (obj, fn) => Object.keys(obj) .filter(k => fn(obj[k], k)) .reduce((acc, key) => ((acc[key] = obj[key]), acc), {}); -const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); -const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); -const pluralize = (val, word, plural = word + 's') => { + const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg)); + const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); + const pluralize = (val, word, plural = word + 's') => { const _pluralize = (num, word, plural = word + 's') => [1, -1].includes(Number(num)) ? word : plural; if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]); return _pluralize(val, word, plural); }; -const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); -const prefix = prop => { + const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); + const prefix = prop => { const capitalizedProp = prop.charAt(0).toUpperCase() + prop.slice(1); const prefixes = ['', 'webkit', 'moz', 'ms', 'o']; const i = prefixes.findIndex( @@ -843,31 +842,31 @@ const prefix = prop => { ); return i !== -1 ? (i === 0 ? prop : prefixes[i] + capitalizedProp) : null; }; -const prettyBytes = (num, precision = 3, addSpace = true) => { + const prettyBytes = (num, precision = 3, addSpace = true) => { const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0]; const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1); const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision)); return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent]; }; -const primes = num => { + const primes = num => { let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2), sqroot = Math.floor(Math.sqrt(num)), numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2); numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y === x))); return arr; }; -const promisify = func => (...args) => + const promisify = func => (...args) => new Promise((resolve, reject) => func(...args, (err, result) => (err ? reject(err) : resolve(result))) ); -const pull = (arr, ...args) => { + const pull = (arr, ...args) => { let argState = Array.isArray(args[0]) ? args[0] : args; let pulled = arr.filter((v, i) => !argState.includes(v)); arr.length = 0; pulled.forEach(v => arr.push(v)); }; -const pullAtIndex = (arr, pullArr) => { + const pullAtIndex = (arr, pullArr) => { let removed = []; let pulled = arr .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v)) @@ -876,7 +875,7 @@ const pullAtIndex = (arr, pullArr) => { pulled.forEach(v => arr.push(v)); return removed; }; -const pullAtValue = (arr, pullArr) => { + const pullAtValue = (arr, pullArr) => { let removed = [], pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)), mutateTo = arr.filter((v, i) => !pullArr.includes(v)); @@ -884,7 +883,7 @@ const pullAtValue = (arr, pullArr) => { mutateTo.forEach(v => arr.push(v)); return removed; }; -const pullBy = (arr, ...args) => { + const pullBy = (arr, ...args) => { const length = args.length; let fn = length > 1 ? args[length - 1] : undefined; fn = typeof fn == 'function' ? (args.pop(), fn) : undefined; @@ -893,23 +892,23 @@ const pullBy = (arr, ...args) => { arr.length = 0; pulled.forEach(v => arr.push(v)); }; -const radsToDegrees = rad => (rad * 180.0) / Math.PI; -const randomHexColorCode = () => { + const radsToDegrees = rad => (rad * 180.0) / Math.PI; + const randomHexColorCode = () => { let n = (Math.random() * 0xfffff * 1000000).toString(16); return '#' + n.slice(0, 6); }; -const randomIntArrayInRange = (min, max, n = 1) => + const randomIntArrayInRange = (min, max, n = 1) => Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); -const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; -const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; - + const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; + const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; + const readFileLines = filename => fs .readFileSync(filename) .toString('UTF8') .split('\n'); -const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i])); -const recordAnimationFrames = (callback, autoStart = true) => { + const rearg = (fn, indexes) => (...args) => fn(...indexes.map(i => args[i])); + const recordAnimationFrames = (callback, autoStart = true) => { let running = true, raf; const stop = () => { @@ -929,29 +928,29 @@ const recordAnimationFrames = (callback, autoStart = true) => { if (autoStart) start(); return { start, stop }; }; -const redirect = (url, asLink = true) => + const redirect = (url, asLink = true) => asLink ? (window.location.href = url) : window.location.replace(url); -const reducedFilter = (data, keys, fn) => + const reducedFilter = (data, keys, fn) => data.filter(fn).map(el => keys.reduce((acc, key) => { acc[key] = el[key]; return acc; }, {}) ); -const reduceSuccessive = (arr, fn, acc) => + const reduceSuccessive = (arr, fn, acc) => arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]); -const reduceWhich = (arr, comparator = (a, b) => a - b) => + const reduceWhich = (arr, comparator = (a, b) => a - b) => arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a)); -const reject = (pred, array) => array.filter((...args) => !pred(...args)); -const remove = (arr, func) => + const reject = (pred, array) => array.filter((...args) => !pred(...args)); + const remove = (arr, func) => Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { - arr.splice(arr.indexOf(val), 1); - return acc.concat(val); - }, []) + arr.splice(arr.indexOf(val), 1); + return acc.concat(val); + }, []) : []; -const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); -const renameKeys = (keysMap, obj) => + const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, ''); + const renameKeys = (keysMap, obj) => Object.keys(obj).reduce( (acc, key) => ({ ...acc, @@ -959,10 +958,10 @@ const renameKeys = (keysMap, obj) => }), {} ); -const reverseString = str => [...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 => { + const reverseString = str => [...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 => { const worker = new Worker( URL.createObjectURL(new Blob([`postMessage((${fn})());`]), { type: 'application/javascript; charset=utf-8' @@ -977,9 +976,9 @@ const runAsync = fn => { }; }); }; -const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); -const sample = arr => arr[Math.floor(Math.random() * arr.length)]; -const sampleSize = ([...arr], n = 1) => { + const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); + const sample = arr => arr[Math.floor(Math.random() * arr.length)]; + const sampleSize = ([...arr], n = 1) => { let m = arr.length; while (m) { const i = Math.floor(Math.random() * m--); @@ -987,14 +986,14 @@ const sampleSize = ([...arr], n = 1) => { } return arr.slice(0, n); }; -const scrollToTop = () => { + const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop; if (c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); } }; -const sdbm = str => { + const sdbm = str => { let arr = str.split(''); return arr.reduce( (hashCode, currentVal) => @@ -1002,16 +1001,16 @@ const sdbm = str => { 0 ); }; -const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; -const setStyle = (el, ruleName, val) => (el.style[ruleName] = val); -const shallowClone = obj => Object.assign({}, obj); -const shank = (arr, index = 0, delCount = 0, ...elements) => + const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; + const setStyle = (el, ruleName, val) => (el.style[ruleName] = val); + const shallowClone = obj => Object.assign({}, obj); + const shank = (arr, index = 0, delCount = 0, ...elements) => arr .slice(0, index) .concat(elements) .concat(arr.slice(index + delCount)); -const show = (...el) => [...el].forEach(e => (e.style.display = '')); -const shuffle = ([...arr]) => { + const show = (...el) => [...el].forEach(e => (e.style.display = '')); + const shuffle = ([...arr]) => { let m = arr.length; while (m) { const i = Math.floor(Math.random() * m--); @@ -1019,8 +1018,8 @@ const shuffle = ([...arr]) => { } return arr; }; -const similarity = (arr, values) => arr.filter(v => values.includes(v)); -const size = val => + const similarity = (arr, values) => arr.filter(v => values.includes(v)); + const size = val => Array.isArray(val) ? val.length : val && typeof val === 'object' @@ -1028,29 +1027,29 @@ const size = val => : typeof val === 'string' ? new Blob([val]).size : 0; -const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); -const smoothScroll = element => + const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); + const smoothScroll = element => document.querySelector(element).scrollIntoView({ behavior: 'smooth' }); -const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join(''); -const sortedIndex = (arr, n) => { + const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join(''); + const sortedIndex = (arr, n) => { const isDescending = arr[0] > arr[arr.length - 1]; const index = arr.findIndex(el => (isDescending ? n >= el : n <= el)); return index === -1 ? arr.length : index; }; -const sortedIndexBy = (arr, n, fn) => { + const sortedIndexBy = (arr, n, fn) => { const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); const val = fn(n); const index = arr.findIndex(el => (isDescending ? val >= fn(el) : val <= fn(el))); return index === -1 ? arr.length : index; }; -const sortedLastIndex = (arr, n) => { + const sortedLastIndex = (arr, n) => { const isDescending = arr[0] > arr[arr.length - 1]; const index = arr.reverse().findIndex(el => (isDescending ? n <= el : n >= el)); return index === -1 ? 0 : arr.length - index; }; -const sortedLastIndexBy = (arr, n, fn) => { + const sortedLastIndexBy = (arr, n, fn) => { const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]); const val = fn(n); const index = arr @@ -1059,21 +1058,21 @@ const sortedLastIndexBy = (arr, n, fn) => { .findIndex(el => (isDescending ? val <= el : val >= el)); return index === -1 ? 0 : arr.length - index; }; -const splitLines = str => str.split(/\r?\n/); + const splitLines = str => str.split(/\r?\n/); const spreadOver = fn => argsArr => fn(...argsArr); -const stableSort = (arr, compare) => + const stableSort = (arr, compare) => arr .map((item, index) => ({ item, index })) .sort((a, b) => compare(a.item, b.item) || a.index - b.index) .map(({ item }) => item); -const standardDeviation = (arr, usePopulation = false) => { + const standardDeviation = (arr, usePopulation = false) => { const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length; return Math.sqrt( arr.reduce((acc, val) => acc.concat((val - mean) ** 2), []).reduce((acc, val) => acc + val, 0) / (arr.length - (usePopulation ? 0 : 1)) ); }; -const stringPermutations = str => { + const stringPermutations = str => { if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; return str .split('') @@ -1083,35 +1082,35 @@ const stringPermutations = str => { [] ); }; -const stripHTMLTags = str => str.replace(/<[^>]*>/g, ''); -const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); -const sumBy = (arr, fn) => + const stripHTMLTags = str => str.replace(/<[^>]*>/g, ''); + const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); + const sumBy = (arr, fn) => arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0); -const sumPower = (end, power = 2, start = 1) => + const sumPower = (end, power = 2, start = 1) => Array(end + 1 - start) .fill(0) .map((x, i) => (i + start) ** power) .reduce((a, b) => a + b, 0); -const symmetricDifference = (a, b) => { + const symmetricDifference = (a, b) => { const sA = new Set(a), sB = new Set(b); return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; }; -const symmetricDifferenceBy = (a, b, fn) => { + const symmetricDifferenceBy = (a, b, fn) => { const sA = new Set(a.map(v => fn(v))), sB = new Set(b.map(v => fn(v))); return [...a.filter(x => !sB.has(fn(x))), ...b.filter(x => !sA.has(fn(x)))]; }; -const symmetricDifferenceWith = (arr, val, comp) => [ + const symmetricDifferenceWith = (arr, val, comp) => [ ...arr.filter(a => val.findIndex(b => comp(a, b)) === -1), ...val.filter(a => arr.findIndex(b => comp(a, b)) === -1) ]; -const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); -const take = (arr, n = 1) => arr.slice(0, n); -const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); + const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); + const take = (arr, n = 1) => arr.slice(0, n); + const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); const takeRightWhile = (arr, func) => arr.reduceRight((acc, el) => (func(el) ? acc : [el, ...acc]), []); -const takeWhile = (arr, func) => { + const takeWhile = (arr, func) => { for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i); return arr; }; @@ -1135,17 +1134,17 @@ const takeWhile = (arr, func) => { } }; }; -const times = (n, fn, context = undefined) => { + const times = (n, fn, context = undefined) => { let i = 0; while (fn.call(context, i) !== false && ++i < n) {} }; -const timeTaken = callback => { + const timeTaken = callback => { console.time('timeTaken'); const r = callback(); console.timeEnd('timeTaken'); return r; }; -const toCamelCase = str => { + const toCamelCase = str => { let s = str && str @@ -1154,23 +1153,23 @@ const toCamelCase = str => { .join(''); return s.slice(0, 1).toLowerCase() + s.slice(1); }; -const toCurrency = (n, curr, LanguageFormat = undefined) => + const toCurrency = (n, curr, LanguageFormat = undefined) => Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n); -const toDecimalMark = num => num.toLocaleString('en-US'); -const toggleClass = (el, className) => el.classList.toggle(className); -const toHash = (object, key) => + const toDecimalMark = num => num.toLocaleString('en-US'); + const toggleClass = (el, className) => el.classList.toggle(className); + const toHash = (object, key) => Array.prototype.reduce.call( object, (acc, data, index) => ((acc[!key ? index : data[key]] = data), acc), {} ); -const toKebabCase = str => + const toKebabCase = str => 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(x => x.toLowerCase()) .join('-'); -const tomorrow = (long = false) => { + const tomorrow = (long = false) => { let t = new Date(); t.setDate(t.getDate() + 1); const ret = `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String( @@ -1178,7 +1177,7 @@ const tomorrow = (long = false) => { ).padStart(2, '0')}`; return !long ? ret : `${ret}T00:00:00`; }; -const toOrdinalSuffix = num => { + const toOrdinalSuffix = num => { const int = parseInt(num), digits = [int % 10, int % 100], ordinals = ['st', 'nd', 'rd', 'th'], @@ -1188,27 +1187,27 @@ const toOrdinalSuffix = num => { ? int + ordinals[digits[0] - 1] : int + ordinals[3]; }; -const toSafeInteger = num => + const toSafeInteger = num => Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)); -const toSnakeCase = str => + const toSnakeCase = str => 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(x => x.toLowerCase()) .join('_'); -const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc); + const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc); const triggerEvent = (el, eventType, detail) => el.dispatchEvent(new CustomEvent(eventType, { detail })); -const truncateString = (str, num) => + const truncateString = (str, num) => str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; -const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]); -const unary = fn => val => fn(val); -const uncurry = (fn, n = 1) => (...args) => { + const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]); + const unary = fn => val => fn(val); + const uncurry = (fn, n = 1) => (...args) => { const next = acc => args => args.reduce((x, y) => x(y), acc); if (n > args.length) throw new RangeError('Arguments too few!'); return next(fn)(args.slice(0, n)); }; -const unescapeHTML = str => + const unescapeHTML = str => str.replace( /&|<|>|'|"/g, tag => @@ -1220,7 +1219,7 @@ const unescapeHTML = str => '"': '"' }[tag] || tag) ); -const unflattenObject = obj => + const unflattenObject = obj => Object.keys(obj).reduce((acc, k) => { if (k.indexOf('.') !== -1) { const keys = k.split('.'); @@ -1236,42 +1235,42 @@ const unflattenObject = obj => } else acc[k] = obj[k]; return acc; }, {}); -const unfold = (fn, seed) => { + const unfold = (fn, seed) => { let result = [], val = [null, seed]; while ((val = fn(val[1]))) result.push(val[0]); return result; }; -const union = (a, b) => Array.from(new Set([...a, ...b])); -const unionBy = (a, b, fn) => { - const s = new Set(a.map(v => fn(v))); + const union = (a, b) => Array.from(new Set([...a, ...b])); + const unionBy = (a, b, fn) => { + const s = new Set(a.map(fn)); return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))])); }; -const unionWith = (a, b, comp) => + const unionWith = (a, b, comp) => Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)])); -const uniqueElements = arr => [...new Set(arr)]; -const uniqueElementsBy = (arr, fn) => + const uniqueElements = arr => [...new Set(arr)]; + const uniqueElementsBy = (arr, fn) => arr.reduce((acc, v) => { if (!acc.some(x => fn(v, x))) acc.push(v); return acc; }, []); -const uniqueElementsByRight = (arr, fn) => + const uniqueElementsByRight = (arr, fn) => arr.reduceRight((acc, v) => { if (!acc.some(x => fn(v, x))) acc.push(v); return acc; }, []); -const uniqueSymmetricDifference = (a, b) => [ + const uniqueSymmetricDifference = (a, b) => [ ...new Set([...a.filter(v => !b.includes(v)), ...b.filter(v => !a.includes(v))]) ]; -const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`); -const unzip = arr => + const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`); + const unzip = arr => arr.reduce( (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), Array.from({ length: Math.max(...arr.map(x => x.length)) }).map(x => []) ); -const unzipWith = (arr, fn) => + const unzipWith = (arr, fn) => arr .reduce( (acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc), @@ -1280,7 +1279,7 @@ const unzipWith = (arr, fn) => }).map(x => []) ) .map(val => fn(...val)); -const URLJoin = (...args) => + const URLJoin = (...args) => args .join('/') .replace(/[\/]+/g, '/') @@ -1289,31 +1288,31 @@ const URLJoin = (...args) => .replace(/\/(\?|&|#[^!])/g, '$1') .replace(/\?/g, '&') .replace('&', '?'); -const UUIDGeneratorBrowser = () => + const UUIDGeneratorBrowser = () => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16) ); - + const UUIDGeneratorNode = () => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16) ); -const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; -const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x); -const without = (arr, ...args) => arr.filter(v => !args.includes(v)); -const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); -const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []); -const yesNo = (val, def = false) => + const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; + const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x); + const without = (arr, ...args) => arr.filter(v => !args.includes(v)); + const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); + const xProd = (a, b) => a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []); + const yesNo = (val, def = false) => /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def; -const zip = (...arrays) => { + const zip = (...arrays) => { const maxLength = Math.max(...arrays.map(x => x.length)); return Array.from({ length: maxLength }).map((_, i) => { return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]); }); }; -const zipObject = (props, values) => + const zipObject = (props, values) => props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {}); -const zipWith = (...array) => { + const zipWith = (...array) => { const fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined; return Array.from( { length: Math.max(...array.map(a => a.length)) }, @@ -1327,6 +1326,7 @@ const zipWith = (...array) => { if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end); return mid; }; + const celsiusToFahrenheit = degrees => 1.8 * degrees + 32; const cleanObj = (obj, keysToKeep = [], childIndicator) => { Object.keys(obj).forEach(key => { if (key === childIndicator) { @@ -1358,6 +1358,7 @@ const zipWith = (...array) => { }, []); return primes ? array.filter(isPrime) : array; }; + const fahrenheitToCelsius = degrees => (degrees - 32) * 5/9; const fibonacciCountUntilNum = num => Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); const fibonacciUntilNum = num => { @@ -1412,6 +1413,7 @@ const zipWith = (...array) => { const dt = new Date(parseInt(arr.toString().substr(6))); return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; }; + const kmphToMph = (kmph) => 0.621371192 * kmph; const levenshteinDistance = (string1, string2) => { if (string1.length === 0) return string2.length; if (string2.length === 0) return string1.length; @@ -1436,6 +1438,7 @@ const zipWith = (...array) => { } return matrix[string2.length][string1.length]; }; + const mphToKmph = (mph) => 1.6093440006146922 * mph; const pipeLog = data => console.log(data) || data; const quickSort = ([n, ...nums], desc) => isNaN(n) @@ -1479,6 +1482,7 @@ const zipWith = (...array) => { msg.voice = window.speechSynthesis.getVoices()[0]; window.speechSynthesis.speak(msg); }; + const squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0); -module.exports = {all,allEqual,any,approximatelyEqual,arrayToCSV,arrayToHtmlList,ary,atob,attempt,average,averageBy,bifurcate,bifurcateBy,bind,bindAll,bindKey,binomialCoefficient,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,composeRight,converge,copyToClipboard,countBy,counter,countOccurrences,createElement,createEventHub,CSVToArray,CSVToJSON,currentURL,curry,dayOfYear,debounce,decapitalize,deepClone,deepFlatten,deepFreeze,defaults,defer,degreesToRads,delay,detectDeviceType,difference,differenceBy,differenceWith,dig,digitize,distance,drop,dropRight,dropRightWhile,dropWhile,elementContains,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,filterNonUniqueBy,findKey,findLast,findLastIndex,findLastKey,flatten,flattenObject,flip,forEachRight,formatDuration,forOwn,forOwnRight,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getColonTimeFromDate,getDaysDiffBetweenDates,getImages,getMeridiemSuffixOfInteger,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,hz,indentString,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,initializeNDArray,inRange,insertAfter,insertBefore,intersection,intersectionBy,intersectionWith,invertKeyValues,is,isAbsoluteURL,isAfterDate,isAnagram,isArrayLike,isBeforeDate,isBoolean,isBrowser,isBrowserTabFocused,isDivisible,isDuplexStream,isEmpty,isEven,isFunction,isLowerCase,isNil,isNull,isNumber,isObject,isObjectLike,isPlainObject,isPrime,isPrimitive,isPromiseLike,isReadableStream,isSameDate,isSorted,isStream,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,isWritableStream,join,JSONtoCSV,JSONToFile,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapString,mapValues,mask,matches,matchesWith,maxBy,maxDate,maxN,median,memoize,merge,minBy,minDate,minN,mostPerformant,negate,nest,nodeListToArray,none,nthArg,nthElement,objectFromPairs,objectToPairs,observeMutations,off,offset,omit,omitBy,on,once,onUserInputChange,orderBy,over,overArgs,pad,palindrome,parseCookie,partial,partialRight,partition,percentile,permutations,pick,pickBy,pipeAsyncFunctions,pipeFunctions,pluralize,powerset,prefix,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,radsToDegrees,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,rearg,recordAnimationFrames,redirect,reducedFilter,reduceSuccessive,reduceWhich,reject,remove,removeNonASCII,renameKeys,reverseString,RGBToHex,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,serializeCookie,setStyle,shallowClone,shank,show,shuffle,similarity,size,sleep,smoothScroll,sortCharactersInString,sortedIndex,sortedIndexBy,sortedLastIndex,sortedLastIndexBy,splitLines,spreadOver,stableSort,standardDeviation,stringPermutations,stripHTMLTags,sum,sumBy,sumPower,symmetricDifference,symmetricDifferenceBy,symmetricDifferenceWith,tail,take,takeRight,takeRightWhile,takeWhile,throttle,times,timeTaken,toCamelCase,toCurrency,toDecimalMark,toggleClass,toHash,toKebabCase,tomorrow,toOrdinalSuffix,toSafeInteger,toSnakeCase,transform,triggerEvent,truncateString,truthCheckCollection,unary,uncurry,unescapeHTML,unflattenObject,unfold,union,unionBy,unionWith,uniqueElements,uniqueElementsBy,uniqueElementsByRight,uniqueSymmetricDifference,untildify,unzip,unzipWith,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,validateNumber,when,without,words,xProd,yesNo,zip,zipObject,zipWith,binarySearch,cleanObj,collatz,countVowels,factors,fibonacciCountUntilNum,fibonacciUntilNum,heronArea,howManyTimes,httpDelete,httpPut,isArmstrongNumber,isSimilar,JSONToDate,levenshteinDistance,pipeLog,quickSort,removeVowels,solveRPN,speechSynthesis} \ No newline at end of file +module.exports = {all,allEqual,any,approximatelyEqual,arrayToCSV,arrayToHtmlList,ary,atob,attempt,average,averageBy,bifurcate,bifurcateBy,bind,bindAll,bindKey,binomialCoefficient,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,composeRight,converge,copyToClipboard,countBy,counter,countOccurrences,createElement,createEventHub,CSVToArray,CSVToJSON,currentURL,curry,dayOfYear,debounce,decapitalize,deepClone,deepFlatten,deepFreeze,defaults,defer,degreesToRads,delay,detectDeviceType,difference,differenceBy,differenceWith,dig,digitize,distance,drop,dropRight,dropRightWhile,dropWhile,elementContains,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,filterNonUniqueBy,findKey,findLast,findLastIndex,findLastKey,flatten,flattenObject,flip,forEachRight,formatDuration,forOwn,forOwnRight,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getColonTimeFromDate,getDaysDiffBetweenDates,getImages,getMeridiemSuffixOfInteger,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,hz,indentString,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,initializeNDArray,inRange,insertAfter,insertBefore,intersection,intersectionBy,intersectionWith,invertKeyValues,is,isAbsoluteURL,isAfterDate,isAnagram,isArrayLike,isBeforeDate,isBoolean,isBrowser,isBrowserTabFocused,isDivisible,isDuplexStream,isEmpty,isEven,isFunction,isLowerCase,isNil,isNull,isNumber,isObject,isObjectLike,isPlainObject,isPrime,isPrimitive,isPromiseLike,isReadableStream,isSameDate,isSorted,isStream,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,isWritableStream,join,JSONtoCSV,JSONToFile,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapString,mapValues,mask,matches,matchesWith,maxBy,maxDate,maxN,median,memoize,merge,minBy,minDate,minN,mostPerformant,negate,nest,nodeListToArray,none,nthArg,nthElement,objectFromPairs,objectToPairs,observeMutations,off,offset,omit,omitBy,on,once,onUserInputChange,orderBy,over,overArgs,pad,palindrome,parseCookie,partial,partialRight,partition,percentile,permutations,pick,pickBy,pipeAsyncFunctions,pipeFunctions,pluralize,powerset,prefix,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,radsToDegrees,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,rearg,recordAnimationFrames,redirect,reducedFilter,reduceSuccessive,reduceWhich,reject,remove,removeNonASCII,renameKeys,reverseString,RGBToHex,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,serializeCookie,setStyle,shallowClone,shank,show,shuffle,similarity,size,sleep,smoothScroll,sortCharactersInString,sortedIndex,sortedIndexBy,sortedLastIndex,sortedLastIndexBy,splitLines,spreadOver,stableSort,standardDeviation,stringPermutations,stripHTMLTags,sum,sumBy,sumPower,symmetricDifference,symmetricDifferenceBy,symmetricDifferenceWith,tail,take,takeRight,takeRightWhile,takeWhile,throttle,times,timeTaken,toCamelCase,toCurrency,toDecimalMark,toggleClass,toHash,toKebabCase,tomorrow,toOrdinalSuffix,toSafeInteger,toSnakeCase,transform,triggerEvent,truncateString,truthCheckCollection,unary,uncurry,unescapeHTML,unflattenObject,unfold,union,unionBy,unionWith,uniqueElements,uniqueElementsBy,uniqueElementsByRight,uniqueSymmetricDifference,untildify,unzip,unzipWith,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,validateNumber,when,without,words,xProd,yesNo,zip,zipObject,zipWith,binarySearch,celsiusToFahrenheit,cleanObj,collatz,countVowels,factors,fahrenheitToCelsius,fibonacciCountUntilNum,fibonacciUntilNum,heronArea,howManyTimes,httpDelete,httpPut,isArmstrongNumber,isSimilar,JSONToDate,kmphToMph,levenshteinDistance,mphToKmph,pipeLog,quickSort,removeVowels,solveRPN,speechSynthesis,squareSum} \ No newline at end of file diff --git a/test/celsiusToFahrenheit/celsiusToFahrenheit.test.js b/test/celsiusToFahrenheit.test.js similarity index 90% rename from test/celsiusToFahrenheit/celsiusToFahrenheit.test.js rename to test/celsiusToFahrenheit.test.js index 42f02c969..5735745c2 100644 --- a/test/celsiusToFahrenheit/celsiusToFahrenheit.test.js +++ b/test/celsiusToFahrenheit.test.js @@ -1,5 +1,5 @@ const expect = require('expect'); -const celsiusToFahrenheit = require('./celsiusToFahrenheit.js'); +const {celsiusToFahrenheit} = require('./_30s.js'); test('celsiusToFahrenheit is a Function', () => { expect(celsiusToFahrenheit).toBeInstanceOf(Function); diff --git a/test/celsiusToFahrenheit/celsiusToFahrenheit.js b/test/celsiusToFahrenheit/celsiusToFahrenheit.js deleted file mode 100644 index 1dd2e7b7d..000000000 --- a/test/celsiusToFahrenheit/celsiusToFahrenheit.js +++ /dev/null @@ -1,2 +0,0 @@ -const celsiusToFahrenheit = degrees => 1.8 * degrees + 32; -module.exports = celsiusToFahrenheit; diff --git a/test/fahrenheitToCelsius/fahrenheitToCelsius.test.js b/test/fahrenheitToCelsius.test.js similarity index 90% rename from test/fahrenheitToCelsius/fahrenheitToCelsius.test.js rename to test/fahrenheitToCelsius.test.js index 0ec80c38c..e22dda3c8 100644 --- a/test/fahrenheitToCelsius/fahrenheitToCelsius.test.js +++ b/test/fahrenheitToCelsius.test.js @@ -1,5 +1,5 @@ const expect = require('expect'); -const fahrenheitToCelsius = require('./fahrenheitToCelsius.js'); +const {fahrenheitToCelsius} = require('./_30s.js'); test('fahrenheitToCelsius is a Function', () => { expect(fahrenheitToCelsius).toBeInstanceOf(Function); diff --git a/test/fahrenheitToCelsius/fahrenheitToCelsius.js b/test/fahrenheitToCelsius/fahrenheitToCelsius.js deleted file mode 100644 index 399fd0d61..000000000 --- a/test/fahrenheitToCelsius/fahrenheitToCelsius.js +++ /dev/null @@ -1,2 +0,0 @@ -const fahrenheitToCelsius = degrees => (degrees - 32) * 5/9; -module.exports = fahrenheitToCelsius; diff --git a/test/kmphToMph/kmphToMph.test.js b/test/kmphToMph.test.js similarity index 82% rename from test/kmphToMph/kmphToMph.test.js rename to test/kmphToMph.test.js index 23923c287..2ab2cf007 100644 --- a/test/kmphToMph/kmphToMph.test.js +++ b/test/kmphToMph.test.js @@ -1,5 +1,5 @@ const expect = require('expect'); -const kmphToMph = require('./kmphToMph.js'); +const {kmphToMph} = require('./_30s.js'); test('kmphToMph is a Function', () => { expect(kmphToMph).toBeInstanceOf(Function); diff --git a/test/kmphToMph/kmphToMph.js b/test/kmphToMph/kmphToMph.js deleted file mode 100644 index 7dc23ac31..000000000 --- a/test/kmphToMph/kmphToMph.js +++ /dev/null @@ -1,2 +0,0 @@ -const kmphToMph = (kmph) => 0.621371192 * kmph; -module.exports = kmphToMph; diff --git a/test/mphToKmph/mphToKmph.test.js b/test/mphToKmph.test.js similarity index 82% rename from test/mphToKmph/mphToKmph.test.js rename to test/mphToKmph.test.js index f5a229623..626d96e28 100644 --- a/test/mphToKmph/mphToKmph.test.js +++ b/test/mphToKmph.test.js @@ -1,5 +1,5 @@ const expect = require('expect'); -const mphToKmph = require('./mphToKmph.js'); +const {mphToKmph} = require('./_30s.js'); test('mphToKmph is a Function', () => { expect(mphToKmph).toBeInstanceOf(Function); diff --git a/test/mphToKmph/mphToKmph.js b/test/mphToKmph/mphToKmph.js deleted file mode 100644 index d4190a376..000000000 --- a/test/mphToKmph/mphToKmph.js +++ /dev/null @@ -1,2 +0,0 @@ -const mphToKmph = (mph) => 1.6093440006146922 * mph; -module.exports = mphToKmph; diff --git a/test/squareSum/squareSum.test.js b/test/squareSum.test.js similarity index 73% rename from test/squareSum/squareSum.test.js rename to test/squareSum.test.js index 447cd90d7..08b60a65c 100644 --- a/test/squareSum/squareSum.test.js +++ b/test/squareSum.test.js @@ -1,5 +1,5 @@ const expect = require('expect'); -const squareSum = require('./squareSum.js'); +const {squareSum} = require('./_30s.js'); test('squareSum is a Function', () => { expect(squareSum).toBeInstanceOf(Function); diff --git a/test/squareSum/squareSum.js b/test/squareSum/squareSum.js deleted file mode 100644 index ed3c4a743..000000000 --- a/test/squareSum/squareSum.js +++ /dev/null @@ -1,2 +0,0 @@ -const squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0); -module.exports = squareSum;