diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md
deleted file mode 100644
index 02b176d69..000000000
--- a/.github/ISSUE_TEMPLATE/bug-report.md
+++ /dev/null
@@ -1,20 +0,0 @@
----
-name: Bug report
-about: Create a report to help us improve
-
----
-
-## Bug description
-
-
-## Steps to reproduce
-
-
-## Expected behavior
-
-
-## Screenshots
-
-
-## Environment
-
diff --git a/.github/ISSUE_TEMPLATE/discussion.md b/.github/ISSUE_TEMPLATE/discussion.md
deleted file mode 100644
index 7a2df3f90..000000000
--- a/.github/ISSUE_TEMPLATE/discussion.md
+++ /dev/null
@@ -1,8 +0,0 @@
----
-name: Discussion
-about: Discuss something with us
-
----
-
-## Description
-
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
deleted file mode 100644
index 59b6f461d..000000000
--- a/.github/ISSUE_TEMPLATE/feature_request.md
+++ /dev/null
@@ -1,9 +0,0 @@
----
-name: Feature request
-about: Suggest an idea for this project
-
----
-
-## Description
-
-
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
deleted file mode 100644
index 67daceacd..000000000
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ /dev/null
@@ -1,15 +0,0 @@
-
-
-## Description
-
-
-
-
-## PR Type
-- [ ] Snippets, Tests & Tags (new snippets, updated snippets, re-tagging of snippets, added/updated tests)
-- [ ] Tools, Scripts & Automation (anything related to files in the scripts folder, Gatsby, website, Travis CI or Netlify)
-- [ ] General, Typos, Misc. & Meta (everything related to content, typos, general stuff and meta files in the repository - e.g. the issue template)
-- [ ] Other (please specify in the description above)
-
-## Guidelines
-- [ ] I have read the guidelines in the [CONTRIBUTING](https://github.com/30-seconds/30-seconds-of-code/blob/master/CONTRIBUTING.md) document.
diff --git a/.mdlrc b/.mdlrc
deleted file mode 100644
index 1399044eb..000000000
--- a/.mdlrc
+++ /dev/null
@@ -1,12 +0,0 @@
-rules "MD003", // header style - atx
- "MD004", // ul list style - asterisk
- "MD009", // no trailing whitespaces
- "MD010", // no hard tabs
- "MD011", // no reversed links
- "MD018", // no space after hash on atx style header
- "MD023", // headers should start on the start of the line
- "MD025", // no multiple h1 headers
- "MD031", // blanks around fences
- "MD038", // no spaces inside code elements
- "MD040" // fenced code blocks need to have a language specified
-style ".mdlrc.style.rb"
diff --git a/.mdlrc.style.rb b/.mdlrc.style.rb
deleted file mode 100644
index 5118afccf..000000000
--- a/.mdlrc.style.rb
+++ /dev/null
@@ -1,7 +0,0 @@
-all
-rule 'header-style', :style => "atx"
-rule 'ul-style', :style => "asterisk"
-
-exclude_rule 'first-header-h1'
-exclude_rule 'first-line-h1'
-exclude_rule 'no-inline-html'
diff --git a/.npmignore b/.npmignore
deleted file mode 100644
index 6201d3eb3..000000000
--- a/.npmignore
+++ /dev/null
@@ -1,29 +0,0 @@
-snippet-template.md
-tag_database
-travis.log
-CONTRIBUTING.md
-COLLABORATING.md
-CODE_OF_CONDUCT.md
-.travis.yml
-.mdlrc.style.rb
-.mdlrc
-.codeclimate.yml
-test/*
-glossary/*
-snippets/*
-src/*
-static/*
-static-parts/*
-snippet_data/*
-snippets_archive/*
-scripts/*
-locale/*
-coverage/*
-docs/*
-.travis/*
-.github/*
-advanced.svg
-package-lock.json
-yarn.lock
-advanced.svg
-sponsored_by_DigitalOcean.png
diff --git a/dist/_30s.es5.js b/dist/_30s.es5.js
deleted file mode 100644
index d3d399521..000000000
--- a/dist/_30s.es5.js
+++ /dev/null
@@ -1,3421 +0,0 @@
-(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (factory((global[''] = global[''] || {}, global['']['/_30s'] = {})));
-}(this, (function (exports) { 'use strict';
-
- function _typeof(obj) {
- if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
- _typeof = function (obj) {
- return typeof obj;
- };
- } else {
- _typeof = function (obj) {
- return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
- };
- }
-
- return _typeof(obj);
- }
-
- function _defineProperty(obj, key, value) {
- if (key in obj) {
- Object.defineProperty(obj, key, {
- value: value,
- enumerable: true,
- configurable: true,
- writable: true
- });
- } else {
- obj[key] = value;
- }
-
- return obj;
- }
-
- function ownKeys(object, enumerableOnly) {
- var keys = Object.keys(object);
-
- if (Object.getOwnPropertySymbols) {
- var symbols = Object.getOwnPropertySymbols(object);
- if (enumerableOnly) symbols = symbols.filter(function (sym) {
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
- });
- keys.push.apply(keys, symbols);
- }
-
- return keys;
- }
-
- function _objectSpread2(target) {
- for (var i = 1; i < arguments.length; i++) {
- var source = arguments[i] != null ? arguments[i] : {};
-
- if (i % 2) {
- ownKeys(source, true).forEach(function (key) {
- _defineProperty(target, key, source[key]);
- });
- } else if (Object.getOwnPropertyDescriptors) {
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
- } else {
- ownKeys(source).forEach(function (key) {
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
- });
- }
- }
-
- return target;
- }
-
- function _slicedToArray(arr, i) {
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
- }
-
- function _toArray(arr) {
- return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest();
- }
-
- function _toConsumableArray(arr) {
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
- }
-
- function _arrayWithoutHoles(arr) {
- if (Array.isArray(arr)) {
- for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
-
- return arr2;
- }
- }
-
- function _arrayWithHoles(arr) {
- if (Array.isArray(arr)) return arr;
- }
-
- function _iterableToArray(iter) {
- if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
- }
-
- function _iterableToArrayLimit(arr, i) {
- var _arr = [];
- var _n = true;
- var _d = false;
- var _e = undefined;
-
- try {
- for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
- _arr.push(_s.value);
-
- if (i && _arr.length === i) break;
- }
- } catch (err) {
- _d = true;
- _e = err;
- } finally {
- try {
- if (!_n && _i["return"] != null) _i["return"]();
- } finally {
- if (_d) throw _e;
- }
- }
-
- return _arr;
- }
-
- function _nonIterableSpread() {
- throw new TypeError("Invalid attempt to spread non-iterable instance");
- }
-
- function _nonIterableRest() {
- throw new TypeError("Invalid attempt to destructure non-iterable instance");
- }
-
- var fs = typeof require !== "undefined" && require('fs');
-
- var crypto = typeof require !== "undefined" && require('crypto');
-
- var all = function all(arr) {
- var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Boolean;
- return arr.every(fn);
- };
- var allEqual = function allEqual(arr) {
- return arr.every(function (val) {
- return val === arr[0];
- });
- };
- var any = function any(arr) {
- var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Boolean;
- return arr.some(fn);
- };
- var approximatelyEqual = function approximatelyEqual(v1, v2) {
- var epsilon = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0.001;
- return Math.abs(v1 - v2) < epsilon;
- };
- var arrayToCSV = function arrayToCSV(arr) {
- var delimiter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';
- return arr.map(function (v) {
- return v.map(function (x) {
- return isNaN(x) ? "\"".concat(x.replace(/"/g, '""'), "\"") : x;
- }).join(delimiter);
- }).join('\n');
- };
- var arrayToHtmlList = function arrayToHtmlList(arr, listID) {
- return function (el) {
- return el = document.querySelector('#' + listID), el.innerHTML += arr.map(function (item) {
- return "
".concat(item, "");
- }).join('');
- }();
- };
- var ary = function ary(fn, n) {
- return function () {
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
- args[_key] = arguments[_key];
- }
-
- return fn.apply(void 0, _toConsumableArray(args.slice(0, n)));
- };
- };
- var atob = function atob(str) {
- return Buffer.from(str, 'base64').toString('binary');
- };
- var attempt = function attempt(fn) {
- try {
- 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);
- } catch (e) {
- return e instanceof Error ? e : new Error(e);
- }
- };
- var average = function average() {
- for (var _len3 = arguments.length, nums = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
- nums[_key3] = arguments[_key3];
- }
-
- return nums.reduce(function (acc, val) {
- return acc + val;
- }, 0) / nums.length;
- };
- var averageBy = function averageBy(arr, fn) {
- return arr.map(typeof fn === 'function' ? fn : function (val) {
- return val[fn];
- }).reduce(function (acc, val) {
- return acc + val;
- }, 0) / arr.length;
- };
- var bifurcate = function bifurcate(arr, filter) {
- return arr.reduce(function (acc, val, i) {
- return acc[filter[i] ? 0 : 1].push(val), acc;
- }, [[], []]);
- };
- var bifurcateBy = function bifurcateBy(arr, fn) {
- return arr.reduce(function (acc, val, i) {
- return acc[fn(val, i) ? 0 : 1].push(val), acc;
- }, [[], []]);
- };
- var bind = function bind(fn, context) {
- 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 _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
- args[_key5] = arguments[_key5];
- }
-
- return fn.apply(context, [].concat(boundArgs, args));
- };
- };
- var bindAll = function bindAll(obj) {
- 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) {
- return f = obj[fn], obj[fn] = function () {
- return f.apply(obj);
- };
- });
- };
- var bindKey = function bindKey(context, fn) {
- 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 _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
- args[_key8] = arguments[_key8];
- }
-
- return context[fn].apply(context, [].concat(boundArgs, args));
- };
- };
- var binomialCoefficient = function 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;
- var res = n;
-
- for (var j = 2; j <= k; j++) {
- res *= (n - j + 1) / j;
- }
-
- return Math.round(res);
- };
- var bottomVisible = function bottomVisible() {
- return document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight);
- };
- var btoa = function btoa(str) {
- return Buffer.from(str, 'binary').toString('base64');
- };
- var byteSize = function byteSize(str) {
- return new Blob([str]).size;
- };
- var call = function call(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) {
- return context[key].apply(context, args);
- };
- };
- var capitalize = function capitalize(_ref) {
- var _ref2 = _toArray(_ref),
- first = _ref2[0],
- rest = _ref2.slice(1);
-
- var lowerRest = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
- return first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
- };
- var capitalizeEveryWord = function capitalizeEveryWord(str) {
- return str.replace(/\b[a-z]/g, function (_char) {
- return _char.toUpperCase();
- });
- };
- var castArray = function castArray(val) {
- return Array.isArray(val) ? val : [val];
- };
- var chainAsync = function chainAsync(fns) {
- var curr = 0;
- var last = fns[fns.length - 1];
-
- var next = function next() {
- var fn = fns[curr++];
- fn === last ? fn() : fn(next);
- };
-
- next();
- };
- var checkProp = function checkProp(predicate, prop) {
- return function (obj) {
- return !!predicate(obj[prop]);
- };
- };
- var chunk = function chunk(arr, size) {
- return Array.from({
- length: Math.ceil(arr.length / size)
- }, function (v, i) {
- return arr.slice(i * size, i * size + size);
- });
- };
- var clampNumber = function clampNumber(num, a, b) {
- return Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
- };
- var cloneRegExp = function cloneRegExp(regExp) {
- return new RegExp(regExp.source, regExp.flags);
- };
- var coalesce = function coalesce() {
- for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) {
- args[_key10] = arguments[_key10];
- }
-
- return args.find(function (_) {
- return ![undefined, null].includes(_);
- });
- };
- var coalesceFactory = function coalesceFactory(valid) {
- return function () {
- for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) {
- args[_key11] = arguments[_key11];
- }
-
- return args.find(valid);
- };
- };
- var collectInto = function collectInto(fn) {
- return function () {
- for (var _len12 = arguments.length, args = new Array(_len12), _key12 = 0; _key12 < _len12; _key12++) {
- args[_key12] = arguments[_key12];
- }
-
- return fn(args);
- };
- };
- var colorize = function colorize() {
- for (var _len13 = arguments.length, args = new Array(_len13), _key13 = 0; _key13 < _len13; _key13++) {
- args[_key13] = arguments[_key13];
- }
-
- return {
- black: "\x1B[30m".concat(args.join(' ')),
- red: "\x1B[31m".concat(args.join(' ')),
- green: "\x1B[32m".concat(args.join(' ')),
- yellow: "\x1B[33m".concat(args.join(' ')),
- blue: "\x1B[34m".concat(args.join(' ')),
- magenta: "\x1B[35m".concat(args.join(' ')),
- cyan: "\x1B[36m".concat(args.join(' ')),
- white: "\x1B[37m".concat(args.join(' ')),
- bgBlack: "\x1B[40m".concat(args.join(' '), "\x1B[0m"),
- bgRed: "\x1B[41m".concat(args.join(' '), "\x1B[0m"),
- bgGreen: "\x1B[42m".concat(args.join(' '), "\x1B[0m"),
- bgYellow: "\x1B[43m".concat(args.join(' '), "\x1B[0m"),
- bgBlue: "\x1B[44m".concat(args.join(' '), "\x1B[0m"),
- bgMagenta: "\x1B[45m".concat(args.join(' '), "\x1B[0m"),
- bgCyan: "\x1B[46m".concat(args.join(' '), "\x1B[0m"),
- bgWhite: "\x1B[47m".concat(args.join(' '), "\x1B[0m")
- };
- };
- var compact = function compact(arr) {
- return arr.filter(Boolean);
- };
- var compactWhitespace = function compactWhitespace(str) {
- return str.replace(/\s{2,}/g, ' ');
- };
- var compose = function compose() {
- for (var _len14 = arguments.length, fns = new Array(_len14), _key14 = 0; _key14 < _len14; _key14++) {
- fns[_key14] = arguments[_key14];
- }
-
- return fns.reduce(function (f, g) {
- return function () {
- return f(g.apply(void 0, arguments));
- };
- });
- };
- var composeRight = function composeRight() {
- for (var _len15 = arguments.length, fns = new Array(_len15), _key15 = 0; _key15 < _len15; _key15++) {
- fns[_key15] = arguments[_key15];
- }
-
- return fns.reduce(function (f, g) {
- return function () {
- return g(f.apply(void 0, arguments));
- };
- });
- };
- var converge = function converge(converger, fns) {
- return function () {
- 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) {
- return fn.apply(null, args);
- })));
- };
- };
- var copyToClipboard = function copyToClipboard(str) {
- var el = document.createElement('textarea');
- el.value = str;
- el.setAttribute('readonly', '');
- el.style.position = 'absolute';
- el.style.left = '-9999px';
- document.body.appendChild(el);
- var 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);
- }
- };
- var countBy = function countBy(arr, fn) {
- return arr.map(typeof fn === 'function' ? fn : function (val) {
- return val[fn];
- }).reduce(function (acc, val) {
- acc[val] = (acc[val] || 0) + 1;
- return acc;
- }, {});
- };
- 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;
-
- var current = start,
- _step = (end - start) * step < 0 ? -step : step,
- timer = setInterval(function () {
- 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;
- };
- var countOccurrences = function countOccurrences(arr, val) {
- return arr.reduce(function (a, v) {
- return v === val ? a + 1 : a;
- }, 0);
- };
- var createDirIfNotExists = function createDirIfNotExists(dir) {
- return !fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined;
- };
- var createElement = function createElement(str) {
- var el = document.createElement('div');
- el.innerHTML = str;
- return el.firstElementChild;
- };
- var createEventHub = function createEventHub() {
- return {
- hub: Object.create(null),
- emit: function emit(event, data) {
- (this.hub[event] || []).forEach(function (handler) {
- return handler(data);
- });
- },
- on: function on(event, handler) {
- if (!this.hub[event]) this.hub[event] = [];
- this.hub[event].push(handler);
- },
- off: function off(event, handler) {
- var i = (this.hub[event] || []).findIndex(function (h) {
- return h === handler;
- });
- if (i > -1) this.hub[event].splice(i, 1);
- if (this.hub[event].length === 0) delete this.hub[event];
- }
- };
- };
- 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;
- };
- var curry = function curry(fn) {
- var arity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : fn.length;
-
- 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));
- };
- var dayOfYear = function dayOfYear(date) {
- return Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
- };
- var debounce = function debounce(fn) {
- var ms = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
- var timeoutId;
- return function () {
- var _this = this;
-
- for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) {
- args[_key18] = arguments[_key18];
- }
-
- clearTimeout(timeoutId);
- timeoutId = setTimeout(function () {
- return fn.apply(_this, args);
- }, ms);
- };
- };
- 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(''));
- };
- var deepClone = function deepClone(obj) {
- if (obj === null) return null;
- var clone = Object.assign({}, obj);
- Object.keys(clone).forEach(function (key) {
- return clone[key] = _typeof(obj[key]) === 'object' ? deepClone(obj[key]) : obj[key];
- });
- return Array.isArray(obj) && obj.length ? (clone.length = obj.length) && Array.from(clone) : Array.isArray(obj) ? Array.from(obj) : clone;
- };
- var deepFlatten = function deepFlatten(arr) {
- var _ref5;
-
- 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]);
- }) || Object.freeze(obj);
- };
- var deepGet = function deepGet(obj, keys) {
- return keys.reduce(function (xs, x) {
- return xs && xs[x] ? xs[x] : null;
- }, obj);
- };
- var deepMapKeys = function deepMapKeys(obj, f) {
- return Array.isArray(obj) ? obj.map(function (val) {
- return deepMapKeys(val, f);
- }) : _typeof(obj) === 'object' ? Object.keys(obj).reduce(function (acc, current) {
- var val = obj[current];
- acc[f(current)] = val !== null && _typeof(val) === 'object' ? deepMapKeys(val, f) : acc[f(current)] = val;
- return acc;
- }, {}) : obj;
- };
- var defaults = function defaults(obj) {
- 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 _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));
- };
- var degreesToRads = function degreesToRads(deg) {
- return deg * Math.PI / 180.0;
- };
- var delay = function delay(fn, wait) {
- 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));
- };
- var detectDeviceType = function detectDeviceType() {
- return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';
- };
- var difference = function difference(a, b) {
- var s = new Set(b);
- return a.filter(function (x) {
- return !s.has(x);
- });
- };
- var differenceBy = function differenceBy(a, b, fn) {
- var s = new Set(b.map(fn));
- return a.map(fn).filter(function (el) {
- return !s.has(el);
- });
- };
- var differenceWith = function differenceWith(arr, val, comp) {
- return arr.filter(function (a) {
- return val.findIndex(function (b) {
- return comp(a, b);
- }) === -1;
- });
- };
- var dig = function dig(obj, target) {
- return target in obj ? obj[target] : Object.values(obj).reduce(function (acc, val) {
- if (acc !== undefined) return acc;
- if (_typeof(val) === 'object') return dig(val, target);
- }, undefined);
- };
- var digitize = function digitize(n) {
- return _toConsumableArray("".concat(n)).map(function (i) {
- return parseInt(i);
- });
- };
- var distance = function distance(x0, y0, x1, y1) {
- return Math.hypot(x1 - x0, y1 - y0);
- };
- var drop = function drop(arr) {
- var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
- return arr.slice(n);
- };
- var dropRight = function dropRight(arr) {
- var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
- return arr.slice(0, -n);
- };
- var dropRightWhile = function dropRightWhile(arr, func) {
- var rightIndex = arr.length;
-
- while (rightIndex-- && !func(arr[rightIndex])) {
- }
-
- return arr.slice(0, rightIndex + 1);
- };
- var dropWhile = function dropWhile(arr, func) {
- while (arr.length > 0 && !func(arr[0])) {
- arr = arr.slice(1);
- }
-
- return arr;
- };
- var elementContains = function elementContains(parent, child) {
- return parent !== child && parent.contains(child);
- };
- var elementIsVisibleInViewport = function elementIsVisibleInViewport(el) {
- var partiallyVisible = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
-
- var _el$getBoundingClient = el.getBoundingClientRect(),
- top = _el$getBoundingClient.top,
- left = _el$getBoundingClient.left,
- bottom = _el$getBoundingClient.bottom,
- right = _el$getBoundingClient.right;
-
- var _window = window,
- innerHeight = _window.innerHeight,
- innerWidth = _window.innerWidth;
- 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(_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;
-
- var _ratings = _slicedToArray(ratings, 2),
- a = _ratings[0],
- b = _ratings[1];
-
- var expectedScore = function expectedScore(self, opponent) {
- return 1 / (1 + Math.pow(10, (opponent - self) / 400));
- };
-
- var newRating = function newRating(rating, i) {
- return (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a));
- };
-
- if (ratings.length === 2) return [newRating(a, 1), newRating(b, 0)];
-
- for (var i = 0, len = ratings.length; i < len; i++) {
- var j = i;
-
- while (j < len - 1) {
- j++;
-
- var _elo = elo([ratings[i], ratings[j]], kFactor);
-
- var _elo2 = _slicedToArray(_elo, 2);
-
- ratings[i] = _elo2[0];
- ratings[j] = _elo2[1];
- }
- }
-
- return ratings;
- };
- var equals = function 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.prototype !== b.prototype) return false;
- var keys = Object.keys(a);
- if (keys.length !== Object.keys(b).length) return false;
- return keys.every(function (k) {
- return equals(a[k], b[k]);
- });
- };
- var escapeHTML = function escapeHTML(str) {
- return str.replace(/[&<>'"]/g, function (tag) {
- return {
- '&': '&',
- '<': '<',
- '>': '>',
- "'": ''',
- '"': '"'
- }[tag] || tag;
- });
- };
- var escapeRegExp = function escapeRegExp(str) {
- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- };
- var everyNth = function everyNth(arr, nth) {
- return arr.filter(function (e, i) {
- return i % nth === nth - 1;
- });
- };
- var extendHex = function extendHex(shortHex) {
- return '#' + shortHex.slice(shortHex.startsWith('#') ? 1 : 0).split('').map(function (x) {
- return x + x;
- }).join('');
- };
- var factorial = function factorial(n) {
- return n < 0 ? function () {
- throw new TypeError('Negative numbers are not allowed!');
- }() : n <= 1 ? 1 : n * factorial(n - 1);
- };
- var fibonacci = function fibonacci(n) {
- return Array.from({
- length: n
- }).reduce(function (acc, val, i) {
- return acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i);
- }, []);
- };
- var filterFalsy = function filterFalsy(arr) {
- return arr.filter(Boolean);
- };
- var filterNonUnique = function filterNonUnique(arr) {
- return arr.filter(function (i) {
- return arr.indexOf(i) === arr.lastIndexOf(i);
- });
- };
- var filterNonUniqueBy = function filterNonUniqueBy(arr, fn) {
- return arr.filter(function (v, i) {
- return arr.every(function (x, j) {
- return i === j === fn(v, x, i, j);
- });
- });
- };
- var findKey = function findKey(obj, fn) {
- return Object.keys(obj).find(function (key) {
- return fn(obj[key], key, obj);
- });
- };
- var findLast = function findLast(arr, fn) {
- return arr.filter(fn).pop();
- };
- var findLastIndex = function findLastIndex(arr, fn) {
- return (arr.map(function (val, i) {
- return [i, val];
- }).filter(function (_ref8) {
- var _ref9 = _slicedToArray(_ref8, 2),
- i = _ref9[0],
- val = _ref9[1];
-
- return fn(val, i, arr);
- }).pop() || [-1])[0];
- };
- var findLastKey = function findLastKey(obj, fn) {
- return Object.keys(obj).reverse().find(function (key) {
- return fn(obj[key], key, obj);
- });
- };
- var flatten = function flatten(arr) {
- var depth = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
- return arr.reduce(function (a, v) {
- return a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v);
- }, []);
- };
- var flattenObject = function flattenObject(obj) {
- var prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
- return Object.keys(obj).reduce(function (acc, k) {
- var 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;
- }, {});
- };
- var flip = function flip(fn) {
- return function (first) {
- 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]));
- };
- };
- var forEachRight = function forEachRight(arr, callback) {
- return arr.slice(0).reverse().forEach(callback);
- };
- var formatDuration = function formatDuration(ms) {
- if (ms < 0) ms = -ms;
- var 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(function (val) {
- return val[1] !== 0;
- }).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 formToObject = function formToObject(form) {
- return Array.from(new FormData(form)).reduce(function (acc, _ref12) {
- var _ref13 = _slicedToArray(_ref12, 2),
- key = _ref13[0],
- value = _ref13[1];
-
- return _objectSpread2({}, acc, _defineProperty({}, key, value));
- }, {});
- };
- 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 frequencies = function frequencies(arr) {
- return arr.reduce(function (a, v) {
- a[v] = a[v] ? a[v] + 1 : 1;
- return a;
- }, {});
- };
- 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();
- };
- var functionName = function functionName(fn) {
- return console.debug(fn.name), fn;
- };
- var functions = function functions(obj) {
- var inherited = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
- return (inherited ? [].concat(_toConsumableArray(Object.keys(obj)), _toConsumableArray(Object.keys(Object.getPrototypeOf(obj)))) : Object.keys(obj)).filter(function (key) {
- return typeof obj[key] === 'function';
- });
- };
- var gcd = function gcd() {
- var _gcd = function _gcd(x, y) {
- return !y ? x : gcd(y, x % y);
- };
-
- for (var _len23 = arguments.length, arr = new Array(_len23), _key23 = 0; _key23 < _len23; _key23++) {
- arr[_key23] = arguments[_key23];
- }
-
- return [].concat(arr).reduce(function (a, b) {
- return _gcd(a, b);
- });
- };
- var geometricProgression = function geometricProgression(end) {
- var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
- var step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2;
- return Array.from({
- length: Math.floor(Math.log(end / start) / Math.log(step)) + 1
- }).map(function (v, i) {
- return start * Math.pow(step, i);
- });
- };
- var get = function get(from) {
- for (var _len24 = arguments.length, selectors = new Array(_len24 > 1 ? _len24 - 1 : 0), _key24 = 1; _key24 < _len24; _key24++) {
- selectors[_key24 - 1] = arguments[_key24];
- }
-
- return [].concat(selectors).map(function (s) {
- return s.replace(/\[([^\[\]]*)\]/g, '.$1.').split('.').filter(function (t) {
- return t !== '';
- }).reduce(function (prev, cur) {
- return prev && prev[cur];
- }, from);
- });
- };
- var getColonTimeFromDate = function getColonTimeFromDate(date) {
- return date.toTimeString().slice(0, 8);
- };
- var getDaysDiffBetweenDates = function getDaysDiffBetweenDates(dateInitial, dateFinal) {
- return (dateFinal - dateInitial) / (1000 * 3600 * 24);
- };
- var getImages = function getImages(el) {
- var includeDuplicates = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
-
- var images = _toConsumableArray(el.getElementsByTagName('img')).map(function (img) {
- return img.getAttribute('src');
- });
-
- return includeDuplicates ? images : _toConsumableArray(new Set(images));
- };
- var getMeridiemSuffixOfInteger = function getMeridiemSuffixOfInteger(num) {
- return num === 0 || num === 24 ? 12 + 'am' : num === 12 ? 12 + 'pm' : num < 12 ? num % 12 + 'am' : num % 12 + 'pm';
- };
- var getScrollPosition = function getScrollPosition() {
- var el = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window;
- return {
- x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
- y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
- };
- };
- var getStyle = function getStyle(el, ruleName) {
- return getComputedStyle(el)[ruleName];
- };
- var getType = function getType(v) {
- return v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
- };
- var getURLParameters = function getURLParameters(url) {
- return (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(function (a, v) {
- return a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a;
- }, {});
- };
- var groupBy = function groupBy(arr, fn) {
- return arr.map(typeof fn === 'function' ? fn : function (val) {
- return val[fn];
- }).reduce(function (acc, val, i) {
- acc[val] = (acc[val] || []).concat(arr[i]);
- return acc;
- }, {});
- };
- var hammingDistance = function hammingDistance(num1, num2) {
- return ((num1 ^ num2).toString(2).match(/1/g) || '').length;
- };
- var hasClass = function hasClass(el, className) {
- return el.classList.contains(className);
- };
- var hasFlags = function hasFlags() {
- for (var _len25 = arguments.length, flags = new Array(_len25), _key25 = 0; _key25 < _len25; _key25++) {
- flags[_key25] = arguments[_key25];
- }
-
- return flags.every(function (flag) {
- return process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag);
- });
- };
- var hashBrowser = function hashBrowser(val) {
- return crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(function (h) {
- var hexes = [],
- view = new DataView(h);
-
- for (var i = 0; i < view.byteLength; i += 4) {
- hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
- }
-
- return hexes.join('');
- });
- };
- var hashNode = function hashNode(val) {
- return new Promise(function (resolve) {
- return setTimeout(function () {
- return resolve(crypto.createHash('sha256').update(val).digest('hex'));
- }, 0);
- });
- };
- var hasKey = function hasKey(obj, keys) {
- return keys.length > 0 && keys.every(function (key) {
- if (_typeof(obj) !== 'object' || !obj.hasOwnProperty(key)) return false;
- obj = obj[key];
- return true;
- });
- };
- var haveSameContents = function haveSameContents(a, b) {
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
-
- try {
- var _loop = function _loop() {
- var v = _step2.value;
- if (a.filter(function (e) {
- return e === v;
- }).length !== b.filter(function (e) {
- return e === v;
- }).length) return {
- v: false
- };
- };
-
- for (var _iterator = new Set([].concat(_toConsumableArray(a), _toConsumableArray(b)))[Symbol.iterator](), _step2; !(_iteratorNormalCompletion = (_step2 = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var _ret = _loop();
-
- if (_typeof(_ret) === "object") return _ret.v;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator["return"] != null) {
- _iterator["return"]();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
-
- return true;
- };
- var head = function head(arr) {
- return arr && arr.length ? arr[0] : undefined;
- };
- var hexToRGB = function hexToRGB(hex) {
- var alpha = false,
- h = hex.slice(hex.startsWith('#') ? 1 : 0);
- if (h.length === 3) h = _toConsumableArray(h).map(function (x) {
- return 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 ? ", ".concat(h & 0x000000ff) : '') + ')';
- };
- var hide = function hide() {
- for (var _len26 = arguments.length, el = new Array(_len26), _key26 = 0; _key26 < _len26; _key26++) {
- el[_key26] = arguments[_key26];
- }
-
- return [].concat(el).forEach(function (e) {
- return e.style.display = 'none';
- });
- };
- var httpGet = function httpGet(url, callback) {
- var err = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : console.error;
- var request = new XMLHttpRequest();
- request.open('GET', url, true);
-
- request.onload = function () {
- return callback(request.responseText);
- };
-
- request.onerror = function () {
- return err(request);
- };
-
- request.send();
- };
- var httpPost = function httpPost(url, data, callback) {
- var err = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : console.error;
- var request = new XMLHttpRequest();
- request.open('POST', url, true);
- request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
-
- request.onload = function () {
- return callback(request.responseText);
- };
-
- request.onerror = function () {
- return err(request);
- };
-
- request.send(data);
- };
- var httpsRedirect = function httpsRedirect() {
- if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
- };
- var hz = function hz(fn) {
- var iterations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100;
- var before = performance.now();
-
- for (var i = 0; i < iterations; i++) {
- fn();
- }
-
- return 1000 * iterations / (performance.now() - before);
- };
- var includesAll = function includesAll(arr, values) {
- return values.every(function (v) {
- return arr.includes(v);
- });
- };
- var includesAny = function includesAny(arr, values) {
- return values.some(function (v) {
- return arr.includes(v);
- });
- };
- var indentString = function indentString(str, count) {
- var indent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ' ';
- return str.replace(/^/gm, indent.repeat(count));
- };
- var indexOfAll = function indexOfAll(arr, val) {
- return arr.reduce(function (acc, el, i) {
- return el === val ? [].concat(_toConsumableArray(acc), [i]) : acc;
- }, []);
- };
- var initial = function initial(arr) {
- return arr.slice(0, -1);
- };
- var initialize2DArray = function initialize2DArray(w, h) {
- var val = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
- return Array.from({
- length: h
- }).map(function () {
- return Array.from({
- length: w
- }).fill(val);
- });
- };
- var initializeArrayWithRange = function initializeArrayWithRange(end) {
- var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
- var step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- return Array.from({
- length: Math.ceil((end - start + 1) / step)
- }, function (v, i) {
- return i * step + start;
- });
- };
- var initializeArrayWithRangeRight = function initializeArrayWithRangeRight(end) {
- var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
- var step = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- return Array.from({
- length: Math.ceil((end + 1 - start) / step)
- }).map(function (v, i, arr) {
- return (arr.length - i - 1) * step + start;
- });
- };
- var initializeArrayWithValues = function initializeArrayWithValues(n) {
- var val = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
- return Array(n).fill(val);
- };
- var initializeNDArray = function initializeNDArray(val) {
- for (var _len27 = arguments.length, args = new Array(_len27 > 1 ? _len27 - 1 : 0), _key27 = 1; _key27 < _len27; _key27++) {
- args[_key27 - 1] = arguments[_key27];
- }
-
- return args.length === 0 ? val : Array.from({
- length: args[0]
- }).map(function () {
- return initializeNDArray.apply(void 0, [val].concat(_toConsumableArray(args.slice(1))));
- });
- };
- var inRange = function inRange(n, start) {
- var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;
-
- if (end && start > end) {
- var _ref14 = [start, end];
- end = _ref14[0];
- start = _ref14[1];
- }
-
- return end == null ? n >= 0 && n < start : n >= start && n < end;
- };
- var insertAfter = function insertAfter(el, htmlString) {
- return el.insertAdjacentHTML('afterend', htmlString);
- };
- var insertBefore = function insertBefore(el, htmlString) {
- return el.insertAdjacentHTML('beforebegin', htmlString);
- };
- var intersection = function intersection(a, b) {
- var s = new Set(b);
- return a.filter(function (x) {
- return s.has(x);
- });
- };
- var intersectionBy = function intersectionBy(a, b, fn) {
- var s = new Set(b.map(fn));
- return a.filter(function (x) {
- return s.has(fn(x));
- });
- };
- var intersectionWith = function intersectionWith(a, b, comp) {
- return a.filter(function (x) {
- return b.findIndex(function (y) {
- return comp(x, y);
- }) !== -1;
- });
- };
- var invertKeyValues = function invertKeyValues(obj, fn) {
- return Object.keys(obj).reduce(function (acc, key) {
- var val = fn ? fn(obj[key]) : obj[key];
- acc[val] = acc[val] || [];
- acc[val].push(key);
- return acc;
- }, {});
- };
- var is = function is(type, val) {
- return ![, null].includes(val) && val.constructor === type;
- };
- var isAbsoluteURL = function isAbsoluteURL(str) {
- return /^[a-z][a-z0-9+.-]*:/.test(str);
- };
- var isAfterDate = function isAfterDate(dateA, dateB) {
- return dateA > dateB;
- };
- var isAnagram = function isAnagram(str1, str2) {
- var normalize = function normalize(str) {
- return str.toLowerCase().replace(/[^a-z0-9]/gi, '').split('').sort().join('');
- };
-
- return normalize(str1) === normalize(str2);
- };
- var isArrayLike = function isArrayLike(obj) {
- return obj != null && typeof obj[Symbol.iterator] === 'function';
- };
- var isBeforeDate = function isBeforeDate(dateA, dateB) {
- return dateA < dateB;
- };
- var isBoolean = function isBoolean(val) {
- return typeof val === 'boolean';
- };
- var isBrowser = function isBrowser() {
- return ![typeof window === "undefined" ? "undefined" : _typeof(window), typeof document === "undefined" ? "undefined" : _typeof(document)].includes('undefined');
- };
- var isBrowserTabFocused = function isBrowserTabFocused() {
- return !document.hidden;
- };
- var isContainedIn = function isContainedIn(a, b) {
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
-
- try {
- var _loop2 = function _loop2() {
- var v = _step3.value;
- if (!b.some(function (e) {
- return e === v;
- }) || a.filter(function (e) {
- return e === v;
- }).length > b.filter(function (e) {
- return e === v;
- }).length) return {
- v: false
- };
- };
-
- for (var _iterator2 = new Set(a)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion2 = (_step3 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var _ret2 = _loop2();
-
- if (_typeof(_ret2) === "object") return _ret2.v;
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
- _iterator2["return"]();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
-
- return true;
- };
- var isDivisible = function isDivisible(dividend, divisor) {
- return dividend % divisor === 0;
- };
- var isDuplexStream = function isDuplexStream(val) {
- return 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';
- };
- var isEmpty = function isEmpty(val) {
- return val == null || !(Object.keys(val) || val).length;
- };
- var isEven = function isEven(num) {
- return num % 2 === 0;
- };
- var isFunction = function isFunction(val) {
- return typeof val === 'function';
- };
- var isLowerCase = function isLowerCase(str) {
- return str === str.toLowerCase();
- };
- var isNegativeZero = function isNegativeZero(val) {
- return val === 0 && 1 / val === -Infinity;
- };
- var isNil = function isNil(val) {
- return val === undefined || val === null;
- };
- var isNull = function isNull(val) {
- return val === null;
- };
- var isNumber = function isNumber(val) {
- return typeof val === 'number' && val === val;
- };
- var isObject = function isObject(obj) {
- return obj === Object(obj);
- };
- var isObjectLike = function isObjectLike(val) {
- return val !== null && _typeof(val) === 'object';
- };
- var isOdd = function isOdd(num) {
- return num % 2 === 1;
- };
- var isPlainObject = function isPlainObject(val) {
- return !!val && _typeof(val) === 'object' && val.constructor === Object;
- };
- var isPowerOfTwo = function isPowerOfTwo(n) {
- return !!n && (n & n - 1) == 0;
- };
- var isPrime = function isPrime(num) {
- var boundary = Math.floor(Math.sqrt(num));
-
- for (var i = 2; i <= boundary; i++) {
- if (num % i === 0) return false;
- }
-
- return num >= 2;
- };
- var isPrimitive = function isPrimitive(val) {
- return Object(val) !== val;
- };
- var isPromiseLike = function isPromiseLike(obj) {
- return obj !== null && (_typeof(obj) === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
- };
- var isReadableStream = function isReadableStream(val) {
- return val !== null && _typeof(val) === 'object' && typeof val.pipe === 'function' && typeof val._read === 'function' && _typeof(val._readableState) === 'object';
- };
- var isSameDate = function isSameDate(dateA, dateB) {
- return dateA.toISOString() === dateB.toISOString();
- };
- var isSorted = function isSorted(arr) {
- var direction = -(arr[0] - arr[1]);
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
-
- try {
- for (var _iterator3 = arr.entries()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion3 = (_step4 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var _step4$value = _slicedToArray(_step4.value, 2),
- i = _step4$value[0],
- val = _step4$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;
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) {
- _iterator3["return"]();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
- };
- var isStream = function isStream(val) {
- return val !== null && _typeof(val) === 'object' && typeof val.pipe === 'function';
- };
- var isString = function isString(val) {
- return typeof val === 'string';
- };
- var isSymbol = function isSymbol(val) {
- return _typeof(val) === 'symbol';
- };
- var isTravisCI = function isTravisCI() {
- return 'TRAVIS' in process.env && 'CI' in process.env;
- };
- var isUndefined = function isUndefined(val) {
- return val === undefined;
- };
- var isUpperCase = function isUpperCase(str) {
- return str === str.toUpperCase();
- };
- var isValidJSON = function isValidJSON(str) {
- try {
- JSON.parse(str);
- return true;
- } catch (e) {
- return false;
- }
- };
- var isWeekday = function isWeekday() {
- var t = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();
- return t.getDay() % 6 !== 0;
- };
- var isWeekend = function isWeekend() {
- var t = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new Date();
- return t.getDay() % 6 === 0;
- };
- var isWritableStream = function isWritableStream(val) {
- return val !== null && _typeof(val) === 'object' && typeof val.pipe === 'function' && typeof val._write === 'function' && _typeof(val._writableState) === 'object';
- };
- var join = function join(arr) {
- var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ',';
- var end = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : separator;
- return arr.reduce(function (acc, val, i) {
- return i === arr.length - 2 ? acc + val + end : i === arr.length - 1 ? acc + val : acc + val + separator;
- }, '');
- };
- 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 ? arr[arr.length - 1] : undefined;
- };
- var lcm = function lcm() {
- var gcd = function gcd(x, y) {
- return !y ? x : gcd(y, x % y);
- };
-
- var _lcm = function _lcm(x, y) {
- return x * y / gcd(x, y);
- };
-
- for (var _len28 = arguments.length, arr = new Array(_len28), _key28 = 0; _key28 < _len28; _key28++) {
- arr[_key28] = arguments[_key28];
- }
-
- return [].concat(arr).reduce(function (a, b) {
- return _lcm(a, b);
- });
- };
- var longestItem = function longestItem() {
- for (var _len29 = arguments.length, vals = new Array(_len29), _key29 = 0; _key29 < _len29; _key29++) {
- vals[_key29] = arguments[_key29];
- }
-
- return vals.reduce(function (a, x) {
- return x.length > a.length ? x : a;
- });
- };
- var lowercaseKeys = function lowercaseKeys(obj) {
- return Object.keys(obj).reduce(function (acc, key) {
- acc[key.toLowerCase()] = obj[key];
- return acc;
- }, {});
- };
- var luhnCheck = function luhnCheck(num) {
- var arr = (num + '').split('').reverse().map(function (x) {
- return parseInt(x);
- });
- var lastDigit = arr.splice(0, 1)[0];
- var sum = arr.reduce(function (acc, val, i) {
- return i % 2 !== 0 ? acc + val : acc + (val * 2 > 9 ? val * 2 - 9 : val * 2);
- }, 0);
- sum += lastDigit;
- return sum % 10 === 0;
- };
- var mapKeys = function mapKeys(obj, fn) {
- return Object.keys(obj).reduce(function (acc, k) {
- acc[fn(obj[k], k, obj)] = obj[k];
- return acc;
- }, {});
- };
- var mapNumRange = function mapNumRange(num, inMin, inMax, outMin, outMax) {
- return (num - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
- };
- var mapObject = function mapObject(arr, fn) {
- return function (a) {
- return a = [arr, arr.map(fn)], a[0].reduce(function (acc, val, ind) {
- return acc[val] = a[1][ind], acc;
- }, {});
- }();
- };
- var mapString = function mapString(str, fn) {
- return str.split('').map(function (c, i) {
- return fn(c, i, str);
- }).join('');
- };
- var mapValues = function mapValues(obj, fn) {
- return Object.keys(obj).reduce(function (acc, k) {
- acc[k] = fn(obj[k], k, obj);
- return acc;
- }, {});
- };
- var mask = function mask(cc) {
- var num = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 4;
- var mask = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '*';
- return "".concat(cc).slice(-num).padStart("".concat(cc).length, mask);
- };
- var matches = function matches(obj, source) {
- return Object.keys(source).every(function (key) {
- return obj.hasOwnProperty(key) && obj[key] === source[key];
- });
- };
- var matchesWith = function matchesWith(obj, source, fn) {
- return Object.keys(source).every(function (key) {
- return obj.hasOwnProperty(key) && fn ? fn(obj[key], source[key], key, obj, source) : obj[key] == source[key];
- });
- };
- var maxBy = function maxBy(arr, fn) {
- return Math.max.apply(Math, _toConsumableArray(arr.map(typeof fn === 'function' ? fn : function (val) {
- return val[fn];
- })));
- };
- var maxDate = function maxDate(dates) {
- return new Date(Math.max.apply(Math, _toConsumableArray(dates)));
- };
- var maxN = function maxN(arr) {
- var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
- return _toConsumableArray(arr).sort(function (a, b) {
- return b - a;
- }).slice(0, n);
- };
- var median = function median(arr) {
- var mid = Math.floor(arr.length / 2),
- nums = _toConsumableArray(arr).sort(function (a, b) {
- return a - b;
- });
-
- return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
- };
- var memoize = function memoize(fn) {
- var cache = new Map();
-
- var cached = function cached(val) {
- return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);
- };
-
- cached.cache = cache;
- return cached;
- };
- var merge = function merge() {
- for (var _len30 = arguments.length, objs = new Array(_len30), _key30 = 0; _key30 < _len30; _key30++) {
- objs[_key30] = arguments[_key30];
- }
-
- return [].concat(objs).reduce(function (acc, obj) {
- return Object.keys(obj).reduce(function (a, k) {
- acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k];
- return acc;
- }, {});
- }, {});
- };
- var midpoint = function midpoint(_ref15, _ref16) {
- var _ref17 = _slicedToArray(_ref15, 2),
- x1 = _ref17[0],
- y1 = _ref17[1];
-
- var _ref18 = _slicedToArray(_ref16, 2),
- x2 = _ref18[0],
- y2 = _ref18[1];
-
- return [(x1 + x2) / 2, (y1 + y2) / 2];
- };
- var minBy = function minBy(arr, fn) {
- return Math.min.apply(Math, _toConsumableArray(arr.map(typeof fn === 'function' ? fn : function (val) {
- return val[fn];
- })));
- };
- var minDate = function minDate(dates) {
- return new Date(Math.min.apply(Math, _toConsumableArray(dates)));
- };
- var minN = function minN(arr) {
- var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
- return _toConsumableArray(arr).sort(function (a, b) {
- return a - b;
- }).slice(0, n);
- };
- var mostFrequent = function mostFrequent(arr) {
- return Object.entries(arr.reduce(function (a, v) {
- a[v] = a[v] ? a[v] + 1 : 1;
- return a;
- }, {})).reduce(function (a, v) {
- return v[1] >= a[1] ? v : a;
- }, [null, 0])[0];
- };
- var mostPerformant = function mostPerformant(fns) {
- var iterations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10000;
- var times = fns.map(function (fn) {
- var before = performance.now();
-
- for (var i = 0; i < iterations; i++) {
- fn();
- }
-
- return performance.now() - before;
- });
- return times.indexOf(Math.min.apply(Math, _toConsumableArray(times)));
- };
- var negate = function negate(func) {
- return function () {
- return !func.apply(void 0, arguments);
- };
- };
- var nest = function nest(items) {
- var id = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
- var link = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'parent_id';
- return items.filter(function (item) {
- return item[link] === id;
- }).map(function (item) {
- return _objectSpread2({}, item, {
- children: nest(items, item.id)
- });
- });
- };
- var nodeListToArray = function nodeListToArray(nodeList) {
- return _toConsumableArray(nodeList);
- };
- var none = function none(arr) {
- var fn = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Boolean;
- return !arr.some(fn);
- };
- var nthArg = function nthArg(n) {
- return function () {
- for (var _len31 = arguments.length, args = new Array(_len31), _key31 = 0; _key31 < _len31; _key31++) {
- args[_key31] = arguments[_key31];
- }
-
- return args.slice(n)[0];
- };
- };
- var nthElement = function nthElement(arr) {
- var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
- return (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];
- };
- var objectFromPairs = function objectFromPairs(arr) {
- return arr.reduce(function (a, _ref19) {
- var _ref20 = _slicedToArray(_ref19, 2),
- key = _ref20[0],
- val = _ref20[1];
-
- return a[key] = val, a;
- }, {});
- };
- var objectToPairs = function objectToPairs(obj) {
- return Object.keys(obj).map(function (k) {
- return [k, obj[k]];
- });
- };
- var objectToQueryString = function objectToQueryString(queryParameters) {
- return queryParameters ? Object.entries(queryParameters).reduce(function (queryString, _ref21, index) {
- var _ref22 = _slicedToArray(_ref21, 2),
- key = _ref22[0],
- val = _ref22[1];
-
- var symbol = queryString.length === 0 ? '?' : '&';
- queryString += typeof val === 'string' ? "".concat(symbol).concat(key, "=").concat(val) : '';
- return queryString;
- }, '') : '';
- };
- var observeMutations = function observeMutations(element, callback, options) {
- var observer = new MutationObserver(function (mutations) {
- return mutations.forEach(function (m) {
- return callback(m);
- });
- });
- observer.observe(element, Object.assign({
- childList: true,
- attributes: true,
- attributeOldValue: true,
- characterData: true,
- characterDataOldValue: true,
- subtree: true
- }, options));
- return observer;
- };
- var off = function off(el, evt, fn) {
- var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
- return el.removeEventListener(evt, fn, opts);
- };
- var offset = function offset(arr, _offset) {
- return [].concat(_toConsumableArray(arr.slice(_offset)), _toConsumableArray(arr.slice(0, _offset)));
- };
- var omit = function omit(obj, arr) {
- return Object.keys(obj).filter(function (k) {
- return !arr.includes(k);
- }).reduce(function (acc, key) {
- return acc[key] = obj[key], acc;
- }, {});
- };
- var omitBy = function omitBy(obj, fn) {
- return Object.keys(obj).filter(function (k) {
- return !fn(obj[k], k);
- }).reduce(function (acc, key) {
- return acc[key] = obj[key], acc;
- }, {});
- };
- var on = function on(el, evt, fn) {
- var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
-
- var delegatorFn = function delegatorFn(e) {
- return 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;
- };
- var once = function once(fn) {
- var called = false;
- return function () {
- if (called) return;
- called = true;
-
- for (var _len32 = arguments.length, args = new Array(_len32), _key32 = 0; _key32 < _len32; _key32++) {
- args[_key32] = arguments[_key32];
- }
-
- return fn.apply(this, args);
- };
- };
- var onUserInputChange = function onUserInputChange(callback) {
- var type = 'mouse',
- lastTime = 0;
-
- var mousemoveHandler = function mousemoveHandler() {
- var now = performance.now();
- if (now - lastTime < 20) type = 'mouse', callback(type), document.removeEventListener('mousemove', mousemoveHandler);
- lastTime = now;
- };
-
- document.addEventListener('touchstart', function () {
- if (type === 'touch') return;
- type = 'touch', callback(type), document.addEventListener('mousemove', mousemoveHandler);
- });
- };
- 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 _ref23 = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]],
- _ref24 = _slicedToArray(_ref23, 2),
- p1 = _ref24[0],
- p2 = _ref24[1];
-
- acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;
- }
-
- return acc;
- }, 0);
- });
- };
- var over = function over() {
- for (var _len33 = arguments.length, fns = new Array(_len33), _key33 = 0; _key33 < _len33; _key33++) {
- fns[_key33] = arguments[_key33];
- }
-
- return function () {
- for (var _len34 = arguments.length, args = new Array(_len34), _key34 = 0; _key34 < _len34; _key34++) {
- args[_key34] = arguments[_key34];
- }
-
- return fns.map(function (fn) {
- return fn.apply(null, args);
- });
- };
- };
- var overArgs = function overArgs(fn, transforms) {
- return function () {
- for (var _len35 = arguments.length, args = new Array(_len35), _key35 = 0; _key35 < _len35; _key35++) {
- args[_key35] = arguments[_key35];
- }
-
- return fn.apply(void 0, _toConsumableArray(args.map(function (val, i) {
- return transforms[i](val);
- })));
- };
- };
- var pad = function pad(str, length) {
- var _char2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ' ';
-
- return str.padStart((str.length + length) / 2, _char2).padEnd(length, _char2);
- };
- var palindrome = function palindrome(str) {
- var s = str.toLowerCase().replace(/[\W_]/g, '');
- return s === _toConsumableArray(s).reverse().join('');
- };
- var parseCookie = function parseCookie(str) {
- return str.split(';').map(function (v) {
- return v.split('=');
- }).reduce(function (acc, v) {
- acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim());
- return acc;
- }, {});
- };
- var partial = function partial(fn) {
- for (var _len36 = arguments.length, partials = new Array(_len36 > 1 ? _len36 - 1 : 0), _key36 = 1; _key36 < _len36; _key36++) {
- partials[_key36 - 1] = arguments[_key36];
- }
-
- return function () {
- for (var _len37 = arguments.length, args = new Array(_len37), _key37 = 0; _key37 < _len37; _key37++) {
- args[_key37] = arguments[_key37];
- }
-
- return fn.apply(void 0, partials.concat(args));
- };
- };
- var partialRight = function partialRight(fn) {
- for (var _len38 = arguments.length, partials = new Array(_len38 > 1 ? _len38 - 1 : 0), _key38 = 1; _key38 < _len38; _key38++) {
- partials[_key38 - 1] = arguments[_key38];
- }
-
- return function () {
- for (var _len39 = arguments.length, args = new Array(_len39), _key39 = 0; _key39 < _len39; _key39++) {
- args[_key39] = arguments[_key39];
- }
-
- return fn.apply(void 0, args.concat(partials));
- };
- };
- var partition = function partition(arr, fn) {
- return arr.reduce(function (acc, val, i, arr) {
- acc[fn(val, i, arr) ? 0 : 1].push(val);
- return acc;
- }, [[], []]);
- };
- var percentile = function percentile(arr, val) {
- return 100 * arr.reduce(function (acc, v) {
- return acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0);
- }, 0) / arr.length;
- };
- var permutations = function permutations(arr) {
- if (arr.length <= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;
- return arr.reduce(function (acc, item, i) {
- return acc.concat(permutations([].concat(_toConsumableArray(arr.slice(0, i)), _toConsumableArray(arr.slice(i + 1)))).map(function (val) {
- return [item].concat(_toConsumableArray(val));
- }));
- }, []);
- };
- var pick = function pick(obj, arr) {
- return arr.reduce(function (acc, curr) {
- return curr in obj && (acc[curr] = obj[curr]), acc;
- }, {});
- };
- var pickBy = function pickBy(obj, fn) {
- return Object.keys(obj).filter(function (k) {
- return fn(obj[k], k);
- }).reduce(function (acc, key) {
- return acc[key] = obj[key], acc;
- }, {});
- };
- var pipeAsyncFunctions = function pipeAsyncFunctions() {
- for (var _len40 = arguments.length, fns = new Array(_len40), _key40 = 0; _key40 < _len40; _key40++) {
- fns[_key40] = arguments[_key40];
- }
-
- return function (arg) {
- return fns.reduce(function (p, f) {
- return p.then(f);
- }, Promise.resolve(arg));
- };
- };
- var pipeFunctions = function pipeFunctions() {
- for (var _len41 = arguments.length, fns = new Array(_len41), _key41 = 0; _key41 < _len41; _key41++) {
- fns[_key41] = arguments[_key41];
- }
-
- return fns.reduce(function (f, g) {
- return function () {
- return g(f.apply(void 0, arguments));
- };
- });
- };
- var pluralize = function pluralize(val, word) {
- var plural = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : word + 's';
-
- var _pluralize = function _pluralize(num, word) {
- var plural = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : word + 's';
- return [1, -1].includes(Number(num)) ? word : plural;
- };
-
- if (_typeof(val) === 'object') return function (num, word) {
- return _pluralize(num, word, val[word]);
- };
- return _pluralize(val, word, plural);
- };
- var powerset = function powerset(arr) {
- return arr.reduce(function (a, v) {
- return a.concat(a.map(function (r) {
- return [v].concat(r);
- }));
- }, [[]]);
- };
- var prefix = function prefix(prop) {
- var capitalizedProp = prop.charAt(0).toUpperCase() + prop.slice(1);
- var prefixes = ['', 'webkit', 'moz', 'ms', 'o'];
- var i = prefixes.findIndex(function (prefix) {
- return typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !== 'undefined';
- });
- return i !== -1 ? i === 0 ? prop : prefixes[i] + capitalizedProp : null;
- };
- var prettyBytes = function prettyBytes(num) {
- var precision = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 3;
- var addSpace = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
- var UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
- if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0];
- var exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1);
- var n = Number(((num < 0 ? -num : num) / Math.pow(1000, exponent)).toPrecision(precision));
- return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent];
- };
- var primes = function primes(num) {
- var arr = Array.from({
- length: num - 1
- }).map(function (x, i) {
- return i + 2;
- }),
- sqroot = Math.floor(Math.sqrt(num)),
- numsTillSqroot = Array.from({
- length: sqroot - 1
- }).map(function (x, i) {
- return i + 2;
- });
- numsTillSqroot.forEach(function (x) {
- return arr = arr.filter(function (y) {
- return y % x !== 0 || y === x;
- });
- });
- return arr;
- };
- var promisify = function promisify(func) {
- return function () {
- for (var _len42 = arguments.length, args = new Array(_len42), _key42 = 0; _key42 < _len42; _key42++) {
- args[_key42] = arguments[_key42];
- }
-
- return new Promise(function (resolve, reject) {
- return func.apply(void 0, args.concat([function (err, result) {
- return err ? reject(err) : resolve(result);
- }]));
- });
- };
- };
- var pull = function pull(arr) {
- for (var _len43 = arguments.length, args = new Array(_len43 > 1 ? _len43 - 1 : 0), _key43 = 1; _key43 < _len43; _key43++) {
- args[_key43 - 1] = arguments[_key43];
- }
-
- var argState = Array.isArray(args[0]) ? args[0] : args;
- var pulled = arr.filter(function (v) {
- return !argState.includes(v);
- });
- arr.length = 0;
- pulled.forEach(function (v) {
- return arr.push(v);
- });
- };
- var pullAtIndex = function pullAtIndex(arr, pullArr) {
- var removed = [];
- var pulled = arr.map(function (v, i) {
- return pullArr.includes(i) ? removed.push(v) : v;
- }).filter(function (v, i) {
- return !pullArr.includes(i);
- });
- arr.length = 0;
- pulled.forEach(function (v) {
- return arr.push(v);
- });
- return removed;
- };
- var pullAtValue = function pullAtValue(arr, pullArr) {
- var removed = [],
- pushToRemove = arr.forEach(function (v, i) {
- return pullArr.includes(v) ? removed.push(v) : v;
- }),
- mutateTo = arr.filter(function (v, i) {
- return !pullArr.includes(v);
- });
- arr.length = 0;
- mutateTo.forEach(function (v) {
- return arr.push(v);
- });
- return removed;
- };
- var pullBy = function pullBy(arr) {
- for (var _len44 = arguments.length, args = new Array(_len44 > 1 ? _len44 - 1 : 0), _key44 = 1; _key44 < _len44; _key44++) {
- args[_key44 - 1] = arguments[_key44];
- }
-
- var length = args.length;
- var fn = length > 1 ? args[length - 1] : undefined;
- fn = typeof fn == 'function' ? (args.pop(), fn) : undefined;
- var argState = (Array.isArray(args[0]) ? args[0] : args).map(function (val) {
- return fn(val);
- });
- var pulled = arr.filter(function (v, i) {
- return !argState.includes(fn(v));
- });
- arr.length = 0;
- pulled.forEach(function (v) {
- return arr.push(v);
- });
- };
- var radsToDegrees = function radsToDegrees(rad) {
- return rad * 180.0 / Math.PI;
- };
- var randomHexColorCode = function randomHexColorCode() {
- var n = (Math.random() * 0xfffff * 1000000).toString(16);
- return '#' + n.slice(0, 6);
- };
- var randomIntArrayInRange = function randomIntArrayInRange(min, max) {
- var n = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- return Array.from({
- length: n
- }, function () {
- return Math.floor(Math.random() * (max - min + 1)) + min;
- });
- };
- var randomIntegerInRange = function randomIntegerInRange(min, max) {
- return Math.floor(Math.random() * (max - min + 1)) + min;
- };
- var randomNumberInRange = function randomNumberInRange(min, max) {
- return Math.random() * (max - min) + min;
- };
- var readFileLines = function readFileLines(filename) {
- return fs.readFileSync(filename).toString('UTF8').split('\n');
- };
- var rearg = function rearg(fn, indexes) {
- return function () {
- for (var _len45 = arguments.length, args = new Array(_len45), _key45 = 0; _key45 < _len45; _key45++) {
- args[_key45] = arguments[_key45];
- }
-
- return fn.apply(void 0, _toConsumableArray(indexes.map(function (i) {
- return args[i];
- })));
- };
- };
- var recordAnimationFrames = function recordAnimationFrames(callback) {
- var autoStart = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
- var running = true,
- raf;
-
- var stop = function stop() {
- running = false;
- cancelAnimationFrame(raf);
- };
-
- var start = function start() {
- running = true;
- run();
- };
-
- var run = function run() {
- raf = requestAnimationFrame(function () {
- callback();
- if (running) run();
- });
- };
-
- if (autoStart) start();
- return {
- start: start,
- stop: stop
- };
- };
- var redirect = function redirect(url) {
- var asLink = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
- 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;
- }, [acc]);
- };
- var reduceWhich = function reduceWhich(arr) {
- var comparator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (a, b) {
- return a - b;
- };
- return arr.reduce(function (a, b) {
- return comparator(a, b) >= 0 ? b : a;
- });
- };
- var reject = function reject(pred, array) {
- return array.filter(function () {
- return !pred.apply(void 0, arguments);
- });
- };
- var remove = function remove(arr, func) {
- return Array.isArray(arr) ? arr.filter(func).reduce(function (acc, val) {
- arr.splice(arr.indexOf(val), 1);
- return acc.concat(val);
- }, []) : [];
- };
- var removeNonASCII = function removeNonASCII(str) {
- return str.replace(/[^\x20-\x7E]/g, '');
- };
- var renameKeys = function renameKeys(keysMap, obj) {
- return Object.keys(obj).reduce(function (acc, key) {
- return _objectSpread2({}, acc, {}, _defineProperty({}, keysMap[key] || key, obj[key]));
- }, {});
- };
- var reverseString = function reverseString(str) {
- 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));
- };
- var runAsync = function runAsync(fn) {
- var worker = new Worker(URL.createObjectURL(new Blob(["postMessage((".concat(fn, ")());")]), {
- type: 'application/javascript; charset=utf-8'
- }));
- return new Promise(function (res, rej) {
- worker.onmessage = function (_ref25) {
- var data = _ref25.data;
- res(data), worker.terminate();
- };
-
- worker.onerror = function (err) {
- rej(err), worker.terminate();
- };
- });
- };
- var runPromisesInSeries = function runPromisesInSeries(ps) {
- return ps.reduce(function (p, next) {
- return p.then(next);
- }, Promise.resolve());
- };
- var sample = function sample(arr) {
- return arr[Math.floor(Math.random() * arr.length)];
- };
- var sampleSize = function sampleSize(_ref26) {
- var _ref27 = _toArray(_ref26),
- arr = _ref27.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 _ref28 = [arr[i], arr[m]];
- arr[m] = _ref28[0];
- arr[i] = _ref28[1];
- }
-
- return arr.slice(0, n);
- };
- var scrollToTop = function scrollToTop() {
- var c = document.documentElement.scrollTop || document.body.scrollTop;
-
- if (c > 0) {
- window.requestAnimationFrame(scrollToTop);
- window.scrollTo(0, c - c / 8);
- }
- };
- var sdbm = function sdbm(str) {
- var arr = str.split('');
- return arr.reduce(function (hashCode, currentVal) {
- return hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode;
- }, 0);
- };
- var serializeCookie = function serializeCookie(name, val) {
- return "".concat(encodeURIComponent(name), "=").concat(encodeURIComponent(val));
- };
- var serializeForm = function serializeForm(form) {
- return Array.from(new FormData(form), function (field) {
- return field.map(encodeURIComponent).join('=');
- }).join('&');
- };
- var setStyle = function setStyle(el, ruleName, val) {
- return el.style[ruleName] = val;
- };
- var shallowClone = function shallowClone(obj) {
- return Object.assign({}, obj);
- };
- var shank = function shank(arr) {
- var index = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
- var delCount = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
-
- for (var _len46 = arguments.length, elements = new Array(_len46 > 3 ? _len46 - 3 : 0), _key46 = 3; _key46 < _len46; _key46++) {
- elements[_key46 - 3] = arguments[_key46];
- }
-
- return arr.slice(0, index).concat(elements).concat(arr.slice(index + delCount));
- };
- var show = function show() {
- for (var _len47 = arguments.length, el = new Array(_len47), _key47 = 0; _key47 < _len47; _key47++) {
- el[_key47] = arguments[_key47];
- }
-
- return [].concat(el).forEach(function (e) {
- return e.style.display = '';
- });
- };
- var shuffle = function shuffle(_ref29) {
- var _ref30 = _toArray(_ref29),
- arr = _ref30.slice(0);
-
- var m = arr.length;
-
- while (m) {
- var i = Math.floor(Math.random() * m--);
- var _ref31 = [arr[i], arr[m]];
- arr[m] = _ref31[0];
- arr[i] = _ref31[1];
- }
-
- return arr;
- };
- var similarity = function similarity(arr, values) {
- return arr.filter(function (v) {
- return values.includes(v);
- });
- };
- var size = function size(val) {
- return 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;
- };
- var sleep = function sleep(ms) {
- return new Promise(function (resolve) {
- return setTimeout(resolve, ms);
- });
- };
- var smoothScroll = function smoothScroll(element) {
- return document.querySelector(element).scrollIntoView({
- behavior: 'smooth'
- });
- };
- var sortCharactersInString = function sortCharactersInString(str) {
- return _toConsumableArray(str).sort(function (a, b) {
- return a.localeCompare(b);
- }).join('');
- };
- var sortedIndex = function sortedIndex(arr, n) {
- var isDescending = arr[0] > arr[arr.length - 1];
- var index = arr.findIndex(function (el) {
- return isDescending ? n >= el : n <= el;
- });
- return index === -1 ? arr.length : index;
- };
- var sortedIndexBy = function sortedIndexBy(arr, n, fn) {
- var isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
- var val = fn(n);
- var index = arr.findIndex(function (el) {
- return isDescending ? val >= fn(el) : val <= fn(el);
- });
- return index === -1 ? arr.length : index;
- };
- var sortedLastIndex = function sortedLastIndex(arr, n) {
- var isDescending = arr[0] > arr[arr.length - 1];
- var index = arr.reverse().findIndex(function (el) {
- return isDescending ? n <= el : n >= el;
- });
- return index === -1 ? 0 : arr.length - index;
- };
- var sortedLastIndexBy = function sortedLastIndexBy(arr, n, fn) {
- var isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
- var val = fn(n);
- var index = arr.map(fn).reverse().findIndex(function (el) {
- return isDescending ? val <= el : val >= el;
- });
- return index === -1 ? 0 : arr.length - index;
- };
- var splitLines = function splitLines(str) {
- return str.split(/\r?\n/);
- };
- var spreadOver = function spreadOver(fn) {
- return function (argsArr) {
- return fn.apply(void 0, _toConsumableArray(argsArr));
- };
- };
- var stableSort = function stableSort(arr, compare) {
- return arr.map(function (item, index) {
- return {
- item: item,
- index: index
- };
- }).sort(function (a, b) {
- return compare(a.item, b.item) || a.index - b.index;
- }).map(function (_ref32) {
- var item = _ref32.item;
- return item;
- });
- };
- var standardDeviation = function standardDeviation(arr) {
- var usePopulation = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
- var mean = arr.reduce(function (acc, val) {
- return acc + val;
- }, 0) / arr.length;
- return Math.sqrt(arr.reduce(function (acc, val) {
- return acc.concat(Math.pow(val - mean, 2));
- }, []).reduce(function (acc, val) {
- return acc + val;
- }, 0) / (arr.length - (usePopulation ? 0 : 1)));
- };
- var stringPermutations = function stringPermutations(str) {
- if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
- return str.split('').reduce(function (acc, letter, i) {
- return acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(function (val) {
- return letter + val;
- }));
- }, []);
- };
- var stripHTMLTags = function stripHTMLTags(str) {
- return str.replace(/<[^>]*>/g, '');
- };
- var sum = function sum() {
- for (var _len48 = arguments.length, arr = new Array(_len48), _key48 = 0; _key48 < _len48; _key48++) {
- arr[_key48] = arguments[_key48];
- }
-
- return [].concat(arr).reduce(function (acc, val) {
- return acc + val;
- }, 0);
- };
- var sumBy = function sumBy(arr, fn) {
- return arr.map(typeof fn === 'function' ? fn : function (val) {
- return val[fn];
- }).reduce(function (acc, val) {
- return acc + val;
- }, 0);
- };
- var sumPower = function sumPower(end) {
- var power = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
- var start = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
- return Array(end + 1 - start).fill(0).map(function (x, i) {
- return Math.pow(i + start, power);
- }).reduce(function (a, b) {
- return a + b;
- }, 0);
- };
- var symmetricDifference = function symmetricDifference(a, b) {
- var sA = new Set(a),
- sB = new Set(b);
- return [].concat(_toConsumableArray(a.filter(function (x) {
- return !sB.has(x);
- })), _toConsumableArray(b.filter(function (x) {
- return !sA.has(x);
- })));
- };
- var symmetricDifferenceBy = function symmetricDifferenceBy(a, b, fn) {
- var sA = new Set(a.map(function (v) {
- return fn(v);
- })),
- sB = new Set(b.map(function (v) {
- return fn(v);
- }));
- return [].concat(_toConsumableArray(a.filter(function (x) {
- return !sB.has(fn(x));
- })), _toConsumableArray(b.filter(function (x) {
- return !sA.has(fn(x));
- })));
- };
- var symmetricDifferenceWith = function symmetricDifferenceWith(arr, val, comp) {
- return [].concat(_toConsumableArray(arr.filter(function (a) {
- return val.findIndex(function (b) {
- return comp(a, b);
- }) === -1;
- })), _toConsumableArray(val.filter(function (a) {
- return arr.findIndex(function (b) {
- return comp(a, b);
- }) === -1;
- })));
- };
- var tail = function tail(arr) {
- return arr.length > 1 ? arr.slice(1) : arr;
- };
- var take = function take(arr) {
- var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
- return arr.slice(0, n);
- };
- var takeRight = function takeRight(arr) {
- var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
- return arr.slice(arr.length - n, arr.length);
- };
- var takeRightWhile = function takeRightWhile(arr, func) {
- return arr.reduceRight(function (acc, el) {
- return func(el) ? acc : [el].concat(_toConsumableArray(acc));
- }, []);
- };
- var takeWhile = function takeWhile(arr, func) {
- var _iteratorNormalCompletion4 = true;
- var _didIteratorError4 = false;
- var _iteratorError4 = undefined;
-
- try {
- for (var _iterator4 = arr.entries()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion4 = (_step5 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
- var _step5$value = _slicedToArray(_step5.value, 2),
- i = _step5$value[0],
- val = _step5$value[1];
-
- if (func(val)) return arr.slice(0, i);
- }
- } catch (err) {
- _didIteratorError4 = true;
- _iteratorError4 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion4 && _iterator4["return"] != null) {
- _iterator4["return"]();
- }
- } finally {
- if (_didIteratorError4) {
- throw _iteratorError4;
- }
- }
- }
-
- return arr;
- };
- var throttle = function throttle(fn, wait) {
- var inThrottle, lastFn, lastTime;
- return function () {
- var 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));
- }
- };
- };
- var times = function times(n, fn) {
- var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
- var i = 0;
-
- 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();
- }).join('');
- return s.slice(0, 1).toLowerCase() + s.slice(1);
- };
- var toCurrency = function toCurrency(n, curr) {
- var LanguageFormat = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
- return Intl.NumberFormat(LanguageFormat, {
- style: 'currency',
- currency: curr
- }).format(n);
- };
- var toDecimalMark = function toDecimalMark(num) {
- 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;
- }, {});
- };
- var toKebabCase = function toKebabCase(str) {
- return str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map(function (x) {
- return x.toLowerCase();
- }).join('-');
- };
- var tomorrow = function tomorrow() {
- var t = new Date();
- t.setDate(t.getDate() + 1);
- return t.toISOString().split('T')[0];
- };
- var toOrdinalSuffix = function toOrdinalSuffix(num) {
- var _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];
- };
- var toSafeInteger = function toSafeInteger(num) {
- return Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER));
- };
- var toSnakeCase = function toSnakeCase(str) {
- return str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map(function (x) {
- return x.toLowerCase();
- }).join('_');
- };
- var toTitleCase = function toTitleCase(str) {
- return 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.charAt(0).toUpperCase() + x.slice(1);
- }).join(' ');
- };
- var transform = function transform(obj, fn, acc) {
- return Object.keys(obj).reduce(function (a, k) {
- return fn(a, obj[k], k, obj);
- }, acc);
- };
- var triggerEvent = function triggerEvent(el, eventType, detail) {
- return el.dispatchEvent(new CustomEvent(eventType, {
- detail: detail
- }));
- };
- var truncateString = function truncateString(str, num) {
- return str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
- };
- var truthCheckCollection = function truthCheckCollection(collection, pre) {
- return collection.every(function (obj) {
- return obj[pre];
- });
- };
- var unary = function unary(fn) {
- return function (val) {
- return fn(val);
- };
- };
- var uncurry = function uncurry(fn) {
- var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
- return function () {
- var next = function next(acc) {
- return function (args) {
- return args.reduce(function (x, y) {
- return x(y);
- }, acc);
- };
- };
-
- for (var _len49 = arguments.length, args = new Array(_len49), _key49 = 0; _key49 < _len49; _key49++) {
- args[_key49] = arguments[_key49];
- }
-
- if (n > args.length) throw new RangeError('Arguments too few!');
- return next(fn)(args.slice(0, n));
- };
- };
- var unescapeHTML = function unescapeHTML(str) {
- return str.replace(/&|<|>|'|"/g, function (tag) {
- return {
- '&': '&',
- '<': '<',
- '>': '>',
- ''': "'",
- '"': '"'
- }[tag] || tag;
- });
- };
- var unflattenObject = function unflattenObject(obj) {
- return Object.keys(obj).reduce(function (acc, k) {
- if (k.indexOf('.') !== -1) {
- var keys = k.split('.');
- Object.assign(acc, JSON.parse('{' + keys.map(function (v, i) {
- return i !== keys.length - 1 ? "\"".concat(v, "\":{") : "\"".concat(v, "\":");
- }).join('') + obj[k] + '}'.repeat(keys.length)));
- } else acc[k] = obj[k];
-
- return acc;
- }, {});
- };
- var unfold = function unfold(fn, seed) {
- var result = [],
- val = [null, seed];
-
- while (val = fn(val[1])) {
- result.push(val[0]);
- }
-
- return result;
- };
- var union = function union(a, b) {
- return Array.from(new Set([].concat(_toConsumableArray(a), _toConsumableArray(b))));
- };
- var unionBy = function unionBy(a, b, fn) {
- var s = new Set(a.map(fn));
- return Array.from(new Set([].concat(_toConsumableArray(a), _toConsumableArray(b.filter(function (x) {
- return !s.has(fn(x));
- })))));
- };
- var unionWith = function unionWith(a, b, comp) {
- return Array.from(new Set([].concat(_toConsumableArray(a), _toConsumableArray(b.filter(function (x) {
- return a.findIndex(function (y) {
- return comp(x, y);
- }) === -1;
- })))));
- };
- var uniqueElements = function uniqueElements(arr) {
- return _toConsumableArray(new Set(arr));
- };
- var uniqueElementsBy = function uniqueElementsBy(arr, fn) {
- return arr.reduce(function (acc, v) {
- if (!acc.some(function (x) {
- return fn(v, x);
- })) acc.push(v);
- return acc;
- }, []);
- };
- var uniqueElementsByRight = function uniqueElementsByRight(arr, fn) {
- return arr.reduceRight(function (acc, v) {
- if (!acc.some(function (x) {
- return fn(v, x);
- })) acc.push(v);
- return acc;
- }, []);
- };
- var uniqueSymmetricDifference = function uniqueSymmetricDifference(a, b) {
- return _toConsumableArray(new Set([].concat(_toConsumableArray(a.filter(function (v) {
- return !b.includes(v);
- })), _toConsumableArray(b.filter(function (v) {
- return !a.includes(v);
- })))));
- };
- var untildify = function untildify(str) {
- return str.replace(/^~($|\/|\\)/, "".concat(require('os').homedir(), "$1"));
- };
- var unzip = function unzip(arr) {
- return arr.reduce(function (acc, val) {
- return val.forEach(function (v, i) {
- return acc[i].push(v);
- }), acc;
- }, Array.from({
- length: Math.max.apply(Math, _toConsumableArray(arr.map(function (x) {
- return x.length;
- })))
- }).map(function (x) {
- return [];
- }));
- };
- var unzipWith = function unzipWith(arr, fn) {
- return arr.reduce(function (acc, val) {
- return val.forEach(function (v, i) {
- return acc[i].push(v);
- }), acc;
- }, Array.from({
- length: Math.max.apply(Math, _toConsumableArray(arr.map(function (x) {
- return x.length;
- })))
- }).map(function (x) {
- return [];
- })).map(function (val) {
- return fn.apply(void 0, _toConsumableArray(val));
- });
- };
- var URLJoin = function URLJoin() {
- for (var _len50 = arguments.length, args = new Array(_len50), _key50 = 0; _key50 < _len50; _key50++) {
- args[_key50] = arguments[_key50];
- }
-
- 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;
- };
- var vectorDistance = function vectorDistance() {
- for (var _len51 = arguments.length, coords = new Array(_len51), _key51 = 0; _key51 < _len51; _key51++) {
- coords[_key51] = arguments[_key51];
- }
-
- var pointLength = Math.trunc(coords.length / 2);
- var sum = coords.slice(0, pointLength).reduce(function (acc, val, i) {
- return acc + Math.pow(val - coords[pointLength + i], 2);
- }, 0);
- return Math.sqrt(sum);
- };
- var weightedSample = function weightedSample(arr, weights) {
- var roll = Math.random();
- return arr[weights.reduce(function (acc, w, i) {
- return i === 0 ? [w] : [].concat(_toConsumableArray(acc), [acc[acc.length - 1] + w]);
- }, []).findIndex(function (v, i, s) {
- return roll >= (i === 0 ? 0 : s[i - 1]) && roll < v;
- })];
- };
- var when = function when(pred, whenTrue) {
- return function (x) {
- return pred(x) ? whenTrue(x) : x;
- };
- };
- var without = function without(arr) {
- 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) {
- return !args.includes(v);
- });
- };
- var words = function words(str) {
- var pattern = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : /[^a-zA-Z-]+/;
- return str.split(pattern).filter(Boolean);
- };
- var xProd = function xProd(a, b) {
- return a.reduce(function (acc, x) {
- return acc.concat(b.map(function (y) {
- return [x, y];
- }));
- }, []);
- };
- var yesNo = function yesNo(val) {
- var def = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
- return /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def;
- };
- var yesterday = function yesterday() {
- var t = new Date();
- t.setDate(t.getDate() - 1);
- return t.toISOString().split('T')[0];
- };
- var zip = function zip() {
- 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) {
- return x.length;
- })));
- return Array.from({
- length: maxLength
- }).map(function (_, i) {
- return Array.from({
- length: arrays.length
- }, function (_, k) {
- return arrays[k][i];
- });
- });
- };
- var zipObject = function zipObject(props, values) {
- return props.reduce(function (obj, prop, index) {
- return obj[prop] = values[index], obj;
- }, {});
- };
- var zipWith = function zipWith() {
- 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;
- return Array.from({
- length: Math.max.apply(Math, _toConsumableArray(array.map(function (a) {
- return a.length;
- })))
- }, function (_, i) {
- return fn ? fn.apply(void 0, _toConsumableArray(array.map(function (a) {
- return a[i];
- }))) : array.map(function (a) {
- return a[i];
- });
- });
- };
- var binarySearch = function binarySearch(arr, val) {
- var start = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
- var end = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : arr.length - 1;
- if (start > end) return -1;
- var mid = Math.floor((start + end) / 2);
- if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);
- if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);
- return mid;
- };
- var celsiusToFahrenheit = function celsiusToFahrenheit(degrees) {
- return 1.8 * degrees + 32;
- };
- var cleanObj = function cleanObj(obj) {
- var keysToKeep = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
- var childIndicator = arguments.length > 2 ? arguments[2] : undefined;
- Object.keys(obj).forEach(function (key) {
- if (key === childIndicator) {
- cleanObj(obj[key], keysToKeep, childIndicator);
- } else if (!keysToKeep.includes(key)) {
- delete obj[key];
- }
- });
- return obj;
- };
- var collatz = function collatz(n) {
- return n % 2 === 0 ? n / 2 : 3 * n + 1;
- };
- var countVowels = function countVowels(str) {
- return (str.match(/[aeiou]/gi) || []).length;
- };
- var factors = function factors(num) {
- var primes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
-
- var isPrime = function isPrime(num) {
- var boundary = Math.floor(Math.sqrt(num));
-
- for (var i = 2; i <= boundary; i++) {
- if (num % i === 0) return false;
- }
-
- return num >= 2;
- };
-
- var isNeg = num < 0;
- num = isNeg ? -num : num;
- var array = Array.from({
- length: num - 1
- }).map(function (val, i) {
- return num % (i + 2) === 0 ? i + 2 : false;
- }).filter(function (val) {
- return val;
- });
- if (isNeg) array = array.reduce(function (acc, val) {
- acc.push(val);
- acc.push(-val);
- return acc;
- }, []);
- return primes ? array.filter(isPrime) : array;
- };
- var fahrenheitToCelsius = function fahrenheitToCelsius(degrees) {
- return (degrees - 32) * 5 / 9;
- };
- var fibonacciCountUntilNum = function fibonacciCountUntilNum(num) {
- return Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
- };
- var fibonacciUntilNum = function fibonacciUntilNum(num) {
- var n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
- return Array.from({
- length: n
- }).reduce(function (acc, val, i) {
- return acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i);
- }, []);
- };
- var heronArea = function heronArea(side_a, side_b, side_c) {
- var p = (side_a + side_b + side_c) / 2;
- return Math.sqrt(p * (p - side_a) * (p - side_b) * (p - side_c));
- };
- var howManyTimes = function howManyTimes(num, divisor) {
- if (divisor === 1 || divisor === -1) return Infinity;
- if (divisor === 0) return 0;
- var i = 0;
-
- while (Number.isInteger(num / divisor)) {
- i++;
- num = num / divisor;
- }
-
- return i;
- };
- var httpDelete = function httpDelete(url, callback) {
- var err = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : console.error;
- var request = new XMLHttpRequest();
- request.open('DELETE', url, true);
-
- request.onload = function () {
- return callback(request);
- };
-
- request.onerror = function () {
- return err(request);
- };
-
- request.send();
- };
- var httpPut = function httpPut(url, data, callback) {
- var err = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : console.error;
- var request = new XMLHttpRequest();
- request.open("PUT", url, true);
- request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
-
- request.onload = function () {
- return callback(request);
- };
-
- request.onerror = function () {
- return err(request);
- };
-
- request.send(data);
- };
- var isArmstrongNumber = function isArmstrongNumber(digits) {
- return function (arr) {
- return arr.reduce(function (a, d) {
- return a + Math.pow(parseInt(d), arr.length);
- }, 0) == digits;
- }((digits + '').split(''));
- };
- var isSimilar = function isSimilar(pattern, str) {
- return _toConsumableArray(str).reduce(function (matchIndex, _char3) {
- return _char3.toLowerCase() === (pattern[matchIndex] || '').toLowerCase() ? matchIndex + 1 : matchIndex;
- }, 0) === pattern.length;
- };
- var JSONToDate = function JSONToDate(arr) {
- var dt = new Date(parseInt(arr.toString().substr(6)));
- return "".concat(dt.getDate(), "/").concat(dt.getMonth() + 1, "/").concat(dt.getFullYear());
- };
- var kmphToMph = function kmphToMph(kmph) {
- return 0.621371192 * kmph;
- };
- var levenshteinDistance = function levenshteinDistance(string1, string2) {
- if (string1.length === 0) return string2.length;
- if (string2.length === 0) return string1.length;
- var matrix = Array(string2.length + 1).fill(0).map(function (x, i) {
- return [i];
- });
- matrix[0] = Array(string1.length + 1).fill(0).map(function (x, i) {
- return i;
- });
-
- for (var i = 1; i <= string2.length; i++) {
- for (var j = 1; j <= string1.length; j++) {
- if (string2[i - 1] === string1[j - 1]) {
- matrix[i][j] = matrix[i - 1][j - 1];
- } else {
- matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1);
- }
- }
- }
-
- return matrix[string2.length][string1.length];
- };
- var mphToKmph = function mphToKmph(mph) {
- return 1.6093440006146922 * mph;
- };
- var pipeLog = function pipeLog(data) {
- return console.log(data) || data;
- };
- var quickSort = function quickSort(_ref33, desc) {
- var _ref34 = _toArray(_ref33),
- n = _ref34[0],
- nums = _ref34.slice(1);
-
- return isNaN(n) ? [] : [].concat(_toConsumableArray(quickSort(nums.filter(function (v) {
- return desc ? v > n : v <= n;
- }), desc)), [n], _toConsumableArray(quickSort(nums.filter(function (v) {
- return !desc ? v > n : v <= n;
- }), desc)));
- };
- var removeVowels = function removeVowels(str) {
- var repl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
- return str.replace(/[aeiou]/gi, repl);
- };
- var solveRPN = function solveRPN(rpn) {
- var OPERATORS = {
- '*': function _(a, b) {
- return a * b;
- },
- '+': function _(a, b) {
- return a + b;
- },
- '-': function _(a, b) {
- return a - b;
- },
- '/': function _(a, b) {
- return a / b;
- },
- '**': function _(a, b) {
- return Math.pow(a, b);
- }
- };
- var _ref35 = [[], rpn.replace(/\^/g, '**').split(/\s+/g).filter(function (el) {
- return !/\s+/.test(el) && el !== '';
- })],
- stack = _ref35[0],
- solve = _ref35[1];
- solve.forEach(function (symbol) {
- if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {
- stack.push(symbol);
- } else if (Object.keys(OPERATORS).includes(symbol)) {
- var _ref36 = [stack.pop(), stack.pop()],
- a = _ref36[0],
- b = _ref36[1];
- stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));
- } else {
- throw "".concat(symbol, " is not a recognized symbol");
- }
- });
- if (stack.length === 1) return stack.pop();else throw "".concat(rpn, " is not a proper RPN. Please check it and try again");
- };
- var speechSynthesis = function speechSynthesis(message) {
- var msg = new SpeechSynthesisUtterance(message);
- msg.voice = window.speechSynthesis.getVoices()[0];
- window.speechSynthesis.speak(msg);
- };
- var squareSum = function squareSum() {
- for (var _len55 = arguments.length, args = new Array(_len55), _key55 = 0; _key55 < _len55; _key55++) {
- args[_key55] = arguments[_key55];
- }
-
- return args.reduce(function (squareSum, number) {
- return squareSum + Math.pow(number, 2);
- }, 0);
- };
-
- 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.checkProp = checkProp;
- 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.compactWhitespace = compactWhitespace;
- exports.compose = compose;
- exports.composeRight = composeRight;
- exports.converge = converge;
- exports.copyToClipboard = copyToClipboard;
- exports.countBy = countBy;
- exports.counter = counter;
- exports.countOccurrences = countOccurrences;
- exports.createDirIfNotExists = createDirIfNotExists;
- exports.createElement = createElement;
- exports.createEventHub = createEventHub;
- exports.CSVToArray = CSVToArray;
- exports.CSVToJSON = CSVToJSON;
- 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.deepGet = deepGet;
- exports.deepMapKeys = deepMapKeys;
- 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.filterFalsy = filterFalsy;
- 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.formatDuration = formatDuration;
- exports.formToObject = formToObject;
- exports.forOwn = forOwn;
- exports.forOwnRight = forOwnRight;
- exports.frequencies = frequencies;
- 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.hasKey = hasKey;
- exports.haveSameContents = haveSameContents;
- exports.head = head;
- exports.hexToRGB = hexToRGB;
- exports.hide = hide;
- exports.httpGet = httpGet;
- exports.httpPost = httpPost;
- exports.httpsRedirect = httpsRedirect;
- exports.hz = hz;
- exports.includesAll = includesAll;
- exports.includesAny = includesAny;
- 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.inRange = inRange;
- 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.isContainedIn = isContainedIn;
- exports.isDivisible = isDivisible;
- exports.isDuplexStream = isDuplexStream;
- exports.isEmpty = isEmpty;
- exports.isEven = isEven;
- exports.isFunction = isFunction;
- exports.isLowerCase = isLowerCase;
- exports.isNegativeZero = isNegativeZero;
- exports.isNil = isNil;
- exports.isNull = isNull;
- exports.isNumber = isNumber;
- exports.isObject = isObject;
- exports.isObjectLike = isObjectLike;
- exports.isOdd = isOdd;
- exports.isPlainObject = isPlainObject;
- exports.isPowerOfTwo = isPowerOfTwo;
- 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.isWeekday = isWeekday;
- exports.isWeekend = isWeekend;
- exports.isWritableStream = isWritableStream;
- exports.join = join;
- exports.JSONtoCSV = JSONtoCSV;
- exports.JSONToFile = JSONToFile;
- exports.last = last;
- exports.lcm = lcm;
- exports.longestItem = longestItem;
- exports.lowercaseKeys = lowercaseKeys;
- exports.luhnCheck = luhnCheck;
- exports.mapKeys = mapKeys;
- exports.mapNumRange = mapNumRange;
- 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.midpoint = midpoint;
- exports.minBy = minBy;
- exports.minDate = minDate;
- exports.minN = minN;
- exports.mostFrequent = mostFrequent;
- 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.objectToQueryString = objectToQueryString;
- exports.observeMutations = observeMutations;
- exports.off = off;
- exports.offset = offset;
- exports.omit = omit;
- exports.omitBy = omitBy;
- exports.on = on;
- exports.once = once;
- exports.onUserInputChange = onUserInputChange;
- 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.reducedFilter = reducedFilter;
- exports.reduceSuccessive = reduceSuccessive;
- exports.reduceWhich = reduceWhich;
- exports.reject = reject;
- exports.remove = remove;
- exports.removeNonASCII = removeNonASCII;
- exports.renameKeys = renameKeys;
- exports.reverseString = reverseString;
- exports.RGBToHex = RGBToHex;
- 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.serializeForm = serializeForm;
- 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.times = times;
- exports.timeTaken = timeTaken;
- exports.toCamelCase = toCamelCase;
- exports.toCurrency = toCurrency;
- exports.toDecimalMark = toDecimalMark;
- exports.toggleClass = toggleClass;
- exports.toHash = toHash;
- exports.toKebabCase = toKebabCase;
- exports.tomorrow = tomorrow;
- exports.toOrdinalSuffix = toOrdinalSuffix;
- exports.toSafeInteger = toSafeInteger;
- exports.toSnakeCase = toSnakeCase;
- exports.toTitleCase = toTitleCase;
- 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.URLJoin = URLJoin;
- exports.UUIDGeneratorBrowser = UUIDGeneratorBrowser;
- exports.UUIDGeneratorNode = UUIDGeneratorNode;
- exports.validateNumber = validateNumber;
- exports.vectorDistance = vectorDistance;
- exports.weightedSample = weightedSample;
- exports.when = when;
- exports.without = without;
- exports.words = words;
- exports.xProd = xProd;
- exports.yesNo = yesNo;
- exports.yesterday = yesterday;
- exports.zip = zip;
- exports.zipObject = zipObject;
- exports.zipWith = zipWith;
- exports.binarySearch = binarySearch;
- exports.celsiusToFahrenheit = celsiusToFahrenheit;
- exports.cleanObj = cleanObj;
- exports.collatz = collatz;
- exports.countVowels = countVowels;
- exports.factors = factors;
- exports.fahrenheitToCelsius = fahrenheitToCelsius;
- exports.fibonacciCountUntilNum = fibonacciCountUntilNum;
- exports.fibonacciUntilNum = fibonacciUntilNum;
- exports.heronArea = heronArea;
- exports.howManyTimes = howManyTimes;
- exports.httpDelete = httpDelete;
- exports.httpPut = httpPut;
- exports.isArmstrongNumber = isArmstrongNumber;
- exports.isSimilar = isSimilar;
- exports.JSONToDate = JSONToDate;
- exports.kmphToMph = kmphToMph;
- exports.levenshteinDistance = levenshteinDistance;
- exports.mphToKmph = mphToKmph;
- exports.pipeLog = pipeLog;
- exports.quickSort = quickSort;
- exports.removeVowels = removeVowels;
- exports.solveRPN = solveRPN;
- exports.speechSynthesis = speechSynthesis;
- exports.squareSum = squareSum;
-
- Object.defineProperty(exports, '__esModule', { value: true });
-
-})));
diff --git a/dist/_30s.es5.min.js b/dist/_30s.es5.min.js
deleted file mode 100644
index 32d85ad01..000000000
--- a/dist/_30s.es5.min.js
+++ /dev/null
@@ -1 +0,0 @@
-(function(e,t){'object'==typeof exports&&'undefined'!=typeof module?t(exports):'function'==typeof define&&define.amd?define(['exports'],t):t((e['']=e['']||{},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 r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,i)}return n}function i(e){for(var t,l=1;ln.filter(function(n){return n===t}).length)return{v:!1}},s=new Set(e)[Symbol.iterator]();!(i=(a=s.next()).done);i=!0)if(o=c(),'object'===t(o))return o.v}catch(e){r=!0,l=e}finally{try{i||null==s['return']||s['return']()}finally{if(r)throw l}}return!0},B=function(e){return null!==e&&'object'===t(e)&&'function'==typeof e.pipe&&'function'==typeof e._read&&'object'===t(e._readableState)&&'function'==typeof e._write&&'object'===t(e._writableState)},D=function(e){return null!==e&&'object'===t(e)},R=function(e){return!!e&&'object'===t(e)&&e.constructor===Object},P=function(e){return null!==e&&('object'===t(e)||'function'==typeof e)&&'function'==typeof e.then},N=function(e){return null!==e&&'object'===t(e)&&'function'==typeof e.pipe&&'function'==typeof e._read&&'object'===t(e._readableState)},z=function(e){return null!==e&&'object'===t(e)&&'function'==typeof e.pipe},F=function(e){return'symbol'===t(e)},U=function(){return'TRAVIS'in process.env&&'CI'in process.env},W=function(e){return null!==e&&'object'===t(e)&&'function'==typeof e.pipe&&'function'==typeof e._write&&'object'===t(e._writableState)},q=function(e,n){var i=2'.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(){l+=a,document.querySelector(e).innerHTML=l,l>=n&&(document.querySelector(e).innerHTML=n),l>=n&&clearInterval(o)},j(b(r/(n-t))));return o},e.countOccurrences=function(e,t){return e.reduce(function(e,n){return n===t?e+1:e},0)},e.createDirIfNotExists=function(e){return x.existsSync(e)?void 0:x.mkdirSync(e)},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:b(e/864e5),hour:b(e/36e5)%24,minute:b(e/6e4)%60,second:b(e/1e3)%60,millisecond:b(e)%1e3};return Object.entries(t).filter(function(e){return 0!==e[1]}).map(function(e){var t=l(e,2),n=t[0],i=t[1];return''.concat(i,' ').concat(n).concat(1===i?'':'s')}).join(', ')},e.formToObject=function(e){return Array.from(new FormData(e)).reduce(function(e,t){var r=l(t,2),a=r[0],o=r[1];return i({},e,n({},a,o))},{})},e.forOwn=function(e,t){return Object.keys(e).forEach(function(n){return t(e[n],n,e)})},e.forOwnRight=function(e,t){return Object.keys(e).reverse().forEach(function(n){return t(e[n],n,e)})},e.frequencies=function(e){return e.reduce(function(e,t){return e[t]=e[t]?e[t]+1:1,e},{})},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(){for(var e=arguments.length,t=Array(e),n=0;nn){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.mapNumRange=function(e,t,n,i,r){return(e-t)*(r-i)/(n-t)+i},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=1=e[1]?t:e},[null,0])[0]},e.mostPerformant=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.orderBy=function(e,t,n){return c(e).sort(function(e,r){return t.reduce(function(t,a,o){if(0===t){var i=n&&'desc'===n[o]?[r[a],e[a]]:[e[a],r[a]],c=l(i,2),s=c[0],d=c[1];t=s>d?1:s=t.length?2===t.length?[t,[t[1],t[0]]]:t:t.reduce(function(n,r,l){return n.concat(e([].concat(c(t.slice(0,l)),c(t.slice(l+1)))).map(function(e){return[r].concat(c(e))}))},[])},e.pick=function(e,t){return t.reduce(function(t,n){return n in e&&(t[n]=e[n]),t},{})},e.pickBy=function(e,t){return Object.keys(e).filter(function(n){return t(e[n],n)}).reduce(function(t,n){return t[n]=e[n],t},{})},e.pipeAsyncFunctions=function(){for(var e=arguments.length,t=Array(e),n=0;nj(e))return e+(i?' ':'')+r[0];var l=_(b(Math.log10(0>e?-e:e)/3),r.length-1),a=+((0>e?-e:e)/m(1e3,l)).toPrecision(t);return(0>e?'-':'')+a+(i?' ':'')+r[l]},e.primes=function(e){var t=Array.from({length:e-1}).map(function(e,t){return t+2}),n=b(u(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),l=e.findIndex(function(e){return i?r>=n(e):r<=n(e)});return-1===l?e.length:l},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),l=e.map(n).reverse().findIndex(function(e){return i?r<=e:r>=e});return-1===l?0:e.length-l},e.splitLines=function(e){return e.split(/\r?\n/)},e.spreadOver=function(e){return function(t){return e.apply(void 0,c(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,l){return n.concat(e(t.slice(0,l)+t.slice(l+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(l,a),r=Date.now())},v(t-(Date.now()-r),0))):(e.apply(l,a),r=Date.now(),n=!0)}},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([].concat(c(e),c(t))))},e.unionBy=function(e,t,n){var i=new Set(e.map(n));return Array.from(new Set([].concat(c(e),c(t.filter(function(e){return!i.has(n(e))})))))},e.unionWith=function(e,t,n){return Array.from(new Set([].concat(c(e),c(t.filter(function(t){return-1===e.findIndex(function(e){return n(t,e)})})))))},e.uniqueElements=function(e){return c(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 c(new Set([].concat(c(e.filter(function(e){return!t.includes(e)})),c(t.filter(function(t){return!e.includes(t)})))))},e.untildify=function(e){return e.replace(/^~($|\/|\\)/,''.concat(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:v.apply(Math,c(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:v.apply(Math,c(e.map(function(e){return e.length})))}).map(function(){return[]})).map(function(e){return t.apply(void 0,c(e))})},e.URLJoin=function(){for(var e=arguments.length,t=Array(e),n=0;n>e/4).toString(16)})},e.UUIDGeneratorNode=function(){return'10000000-1000-4000-8000-100000000000'.replace(/[018]/g,function(e){return(e^C.randomBytes(1)[0]&15>>e/4).toString(16)})},e.validateNumber=function(e){return!isNaN(parseFloat(e))&&isFinite(e)&&+e==e},e.vectorDistance=function(){for(var e=arguments.length,t=Array(e),n=0;n=(0===t?0:i[t-1])&&nr)return-1;var l=b((i+r)/2);return t[l]>n?e(t,n,i,l-1):t[l]e;e=i?-e:e;var r=Array.from({length:e-1}).map(function(t,n){return 0==e%(n+2)&&n+2}).filter(function(e){return e});return i&&(r=r.reduce(function(e,t){return e.push(t),e.push(-t),e},[])),t?r.filter(n):r},e.fahrenheitToCelsius=function(e){return 5*(e-32)/9},e.fibonacciCountUntilNum=function(e){return S(y(2.23606797749979*e+1/2)/0.48121182505960347)},e.fibonacciUntilNum=function(e){var t=S(y(2.23606797749979*e+1/2)/0.48121182505960347);return Array.from({length:t}).reduce(function(e,t,n){return e.concat(1l:e<=l}),i)),[l],c(e(n.filter(function(e){return i?e<=l:e>l}),i)))},e.removeVowels=function(e){var t=1 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 => (isNaN(x) ? `"${x.replace(/"/g, '""')}"` : 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 last = fns[fns.length - 1];
- const next = () => {
- const fn = fns[curr++];
- fn === last ? fn() : fn(next);
- };
- next();
-};
-const checkProp = (predicate, prop) => obj => !!predicate(obj[prop]);
-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 compactWhitespace = str => str.replace(/\s{2,}/g, ' ');
-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 createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
-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);
- if (this.hub[event].length === 0) delete this.hub[event];
- }
-});
-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 => {
- if (obj === null) return null;
- 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) && obj.length
- ? (clone.length = obj.length) && Array.from(clone)
- : Array.isArray(obj)
- ? Array.from(obj)
- : 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 deepGet = (obj, keys) => keys.reduce((xs, x) => (xs && xs[x] ? xs[x] : null), obj);
-const deepMapKeys = (obj, f) =>
- Array.isArray(obj)
- ? obj.map(val => deepMapKeys(val, f))
- : typeof obj === 'object'
- ? Object.keys(obj).reduce((acc, current) => {
- const val = obj[current];
- acc[f(current)] =
- val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);
- return acc;
- }, {})
- : 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.map(fn).filter(el => !s.has(el));
-};
-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) => {
- let rightIndex = arr.length;
- while (rightIndex-- && !func(arr[rightIndex]));
- return arr.slice(0, rightIndex + 1);
-};
-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.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 filterFalsy = arr => arr.filter(Boolean);
-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() || [-1])[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 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 formToObject = form =>
- Array.from(new FormData(form)).reduce(
- (acc, [key, value]) => ({
- ...acc,
- [key]: value
- }),
- {}
- );
-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 frequencies = arr =>
- arr.reduce((a, v) => {
- a[v] = a[v] ? a[v] + 1 : 1;
- return a;
- }, {});
-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 hasKey = (obj, keys) => {
- return (
- keys.length > 0 &&
- keys.every(key => {
- if (typeof obj !== 'object' || !obj.hasOwnProperty(key)) return false;
- obj = obj[key];
- return true;
- })
- );
-};
-const haveSameContents = (a, b) => {
- for (const v of new Set([...a, ...b]))
- if (a.filter(e => e === v).length !== b.filter(e => e === v).length) return false;
- return true;
-};
-const head = arr => (arr && arr.length ? arr[0] : undefined);
-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 = (...el) => [...el].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 includesAll = (arr, values) => values.every(v => arr.includes(v));
-const includesAny = (arr, values) => values.some(v => arr.includes(v));
-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 isContainedIn = (a, b) => {
- for (const v of new Set(a)) {
- if (!b.some(e => e === v) || a.filter(e => e === v).length > b.filter(e => e === v).length)
- return false;
- }
- return true;
-};
-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 isNegativeZero = val => val === 0 && 1 / val === -Infinity;
-const isNil = val => val === undefined || val === null;
-const isNull = val => val === null;
-const isNumber = val => typeof val === 'number' && val === val;
-const isObject = obj => obj === Object(obj);
-const isObjectLike = val => val !== null && typeof val === 'object';
-const isOdd = num => num % 2 === 1;
-const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;
-const isPowerOfTwo = n => !!n && (n & (n - 1)) == 0;
-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 = str => {
- try {
- JSON.parse(str);
- return true;
- } catch (e) {
- return false;
- }
-};
-const isWeekday = (t = new Date()) => {
- return t.getDay() % 6 !== 0;
-};
-const isWeekend = (t = new Date()) => {
- return t.getDay() % 6 === 0;
-};
-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 ? arr[arr.length - 1] : undefined);
-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 = (...vals) => 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 ? val * 2 - 9 : val * 2)), 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 mapNumRange = (num, inMin, inMax, outMin, outMax) =>
- ((num - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
-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(...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 midpoint = ([x1, y1], [x2, y2]) => [(x1 + x2) / 2, (y1 + y2) / 2];
-const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
-const minDate = dates => new Date(Math.min(...dates));
-const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
-const mostFrequent = arr =>
- Object.entries(
- arr.reduce((a, v) => {
- a[v] = a[v] ? a[v] + 1 : 1;
- return a;
- }, {})
- ).reduce((a, v) => (v[1] >= a[1] ? v : a), [null, 0])[0];
-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 objectToQueryString = queryParameters => {
- return queryParameters
- ? Object.entries(queryParameters).reduce((queryString, [key, val], index) => {
- const symbol = queryString.length === 0 ? '?' : '&';
- queryString += typeof val === 'string' ? `${symbol}${key}=${val}` : '';
- return queryString;
- }, '')
- : '';
-};
-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 => !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 serializeForm = form =>
- Array.from(new FormData(form), field => field.map(encodeURIComponent).join('=')).join('&');
-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 = () => {
- let t = new Date();
- t.setDate(t.getDate() + 1);
- return t.toISOString().split('T')[0];
-};
-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 toTitleCase = 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.charAt(0).toUpperCase() + x.slice(1))
- .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 vectorDistance = (...coords) => {
- let pointLength = Math.trunc(coords.length / 2);
- let sum = coords
- .slice(0, pointLength)
- .reduce((acc, val, i) => acc + Math.pow(val - coords[pointLength + i], 2), 0);
- return Math.sqrt(sum);
-};
-const weightedSample = (arr, weights) => {
- let roll = Math.random();
- return arr[
- weights
- .reduce((acc, w, i) => (i === 0 ? [w] : [...acc, acc[acc.length - 1] + w]), [])
- .findIndex((v, i, s) => roll >= (i === 0 ? 0 : s[i - 1]) && roll < v)
- ];
-};
-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 yesterday = () => {
- let t = new Date();
- t.setDate(t.getDate() - 1);
- return t.toISOString().split('T')[0];
-};
-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 binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
- if (start > end) return -1;
- const mid = Math.floor((start + end) / 2);
- if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);
- 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) {
- cleanObj(obj[key], keysToKeep, childIndicator);
- } else if (!keysToKeep.includes(key)) {
- delete obj[key];
- }
- });
- return obj;
-};
-const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);
-const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
-const factors = (num, primes = false) => {
- const isPrime = num => {
- const boundary = Math.floor(Math.sqrt(num));
- for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
- return num >= 2;
- };
- const isNeg = num < 0;
- num = isNeg ? -num : num;
- let array = Array.from({ length: num - 1 })
- .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))
- .filter(val => val);
- if (isNeg)
- array = array.reduce((acc, val) => {
- acc.push(val);
- acc.push(-val);
- return acc;
- }, []);
- return primes ? array.filter(isPrime) : array;
-};
-const 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 => {
- let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
- return Array.from({ length: n }).reduce(
- (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
- []
- );
-};
-const heronArea = (side_a, side_b, side_c) => {
- const p = (side_a + side_b + side_c) / 2;
- return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))
- };
-const howManyTimes = (num, divisor) => {
- if (divisor === 1 || divisor === -1) return Infinity;
- if (divisor === 0) return 0;
- let i = 0;
- while (Number.isInteger(num / divisor)) {
- i++;
- num = num / divisor;
- }
- return i;
-};
-const httpDelete = (url, callback, err = console.error) => {
- const request = new XMLHttpRequest();
- request.open('DELETE', url, true);
- request.onload = () => callback(request);
- request.onerror = () => err(request);
- request.send();
-};
-const httpPut = (url, data, callback, err = console.error) => {
- const request = new XMLHttpRequest();
- request.open("PUT", url, true);
- request.setRequestHeader('Content-type','application/json; charset=utf-8');
- request.onload = () => callback(request);
- request.onerror = () => err(request);
- request.send(data);
-};
-const isArmstrongNumber = digits =>
- (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
- (digits + '').split('')
- );
-const isSimilar = (pattern, str) =>
- [...str].reduce(
- (matchIndex, char) =>
- char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase()
- ? matchIndex + 1
- : matchIndex,
- 0
- ) === pattern.length;
-const JSONToDate = arr => {
- 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;
- let matrix = Array(string2.length + 1)
- .fill(0)
- .map((x, i) => [i]);
- matrix[0] = Array(string1.length + 1)
- .fill(0)
- .map((x, i) => i);
- for (let i = 1; i <= string2.length; i++) {
- for (let j = 1; j <= string1.length; j++) {
- if (string2[i - 1] === string1[j - 1]) {
- matrix[i][j] = matrix[i - 1][j - 1];
- } else {
- matrix[i][j] = Math.min(
- matrix[i - 1][j - 1] + 1,
- matrix[i][j - 1] + 1,
- matrix[i - 1][j] + 1
- );
- }
- }
- }
- 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)
- ? []
- : [
- ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),
- n,
- ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)
- ];
-const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);
-const solveRPN = rpn => {
- const OPERATORS = {
- '*': (a, b) => a * b,
- '+': (a, b) => a + b,
- '-': (a, b) => a - b,
- '/': (a, b) => a / b,
- '**': (a, b) => a ** b
- };
- const [stack, solve] = [
- [],
- rpn
- .replace(/\^/g, '**')
- .split(/\s+/g)
- .filter(el => !/\s+/.test(el) && el !== '')
- ];
- solve.forEach(symbol => {
- if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {
- stack.push(symbol);
- } else if (Object.keys(OPERATORS).includes(symbol)) {
- const [a, b] = [stack.pop(), stack.pop()];
- stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));
- } else {
- throw `${symbol} is not a recognized symbol`;
- }
- });
- if (stack.length === 1) return stack.pop();
- else throw `${rpn} is not a proper RPN. Please check it and try again`;
-};
-const speechSynthesis = message => {
- const msg = new SpeechSynthesisUtterance(message);
- msg.voice = window.speechSynthesis.getVoices()[0];
- window.speechSynthesis.speak(msg);
-};
-const squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0);
-
-export { 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, checkProp, chunk, clampNumber, cloneRegExp, coalesce, coalesceFactory, collectInto, colorize, compact, compactWhitespace, compose, composeRight, converge, copyToClipboard, countBy, counter, countOccurrences, createDirIfNotExists, createElement, createEventHub, CSVToArray, CSVToJSON, currentURL, curry, dayOfYear, debounce, decapitalize, deepClone, deepFlatten, deepFreeze, deepGet, deepMapKeys, 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, filterFalsy, filterNonUnique, filterNonUniqueBy, findKey, findLast, findLastIndex, findLastKey, flatten, flattenObject, flip, forEachRight, formatDuration, formToObject, forOwn, forOwnRight, frequencies, fromCamelCase, functionName, functions, gcd, geometricProgression, get, getColonTimeFromDate, getDaysDiffBetweenDates, getImages, getMeridiemSuffixOfInteger, getScrollPosition, getStyle, getType, getURLParameters, groupBy, hammingDistance, hasClass, hasFlags, hashBrowser, hashNode, hasKey, haveSameContents, head, hexToRGB, hide, httpGet, httpPost, httpsRedirect, hz, includesAll, includesAny, indentString, indexOfAll, initial, initialize2DArray, initializeArrayWithRange, initializeArrayWithRangeRight, initializeArrayWithValues, initializeNDArray, inRange, insertAfter, insertBefore, intersection, intersectionBy, intersectionWith, invertKeyValues, is, isAbsoluteURL, isAfterDate, isAnagram, isArrayLike, isBeforeDate, isBoolean, isBrowser, isBrowserTabFocused, isContainedIn, isDivisible, isDuplexStream, isEmpty, isEven, isFunction, isLowerCase, isNegativeZero, isNil, isNull, isNumber, isObject, isObjectLike, isOdd, isPlainObject, isPowerOfTwo, isPrime, isPrimitive, isPromiseLike, isReadableStream, isSameDate, isSorted, isStream, isString, isSymbol, isTravisCI, isUndefined, isUpperCase, isValidJSON, isWeekday, isWeekend, isWritableStream, join, JSONtoCSV, JSONToFile, last, lcm, longestItem, lowercaseKeys, luhnCheck, mapKeys, mapNumRange, mapObject, mapString, mapValues, mask, matches, matchesWith, maxBy, maxDate, maxN, median, memoize, merge, midpoint, minBy, minDate, minN, mostFrequent, mostPerformant, negate, nest, nodeListToArray, none, nthArg, nthElement, objectFromPairs, objectToPairs, objectToQueryString, 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, serializeForm, 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, toTitleCase, transform, triggerEvent, truncateString, truthCheckCollection, unary, uncurry, unescapeHTML, unflattenObject, unfold, union, unionBy, unionWith, uniqueElements, uniqueElementsBy, uniqueElementsByRight, uniqueSymmetricDifference, untildify, unzip, unzipWith, URLJoin, UUIDGeneratorBrowser, UUIDGeneratorNode, validateNumber, vectorDistance, weightedSample, when, without, words, xProd, yesNo, yesterday, 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 };
diff --git a/dist/_30s.js b/dist/_30s.js
deleted file mode 100644
index e965d3881..000000000
--- a/dist/_30s.js
+++ /dev/null
@@ -1,1991 +0,0 @@
-(function (global, factory) {
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
- (factory((global[''] = global[''] || {}, global['']['/_30s'] = {})));
-}(this, (function (exports) { 'use strict';
-
- const fs = typeof require !== "undefined" && require('fs');
- const crypto = typeof require !== "undefined" && require('crypto');
-
- 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 => (isNaN(x) ? `"${x.replace(/"/g, '""')}"` : 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 last = fns[fns.length - 1];
- const next = () => {
- const fn = fns[curr++];
- fn === last ? fn() : fn(next);
- };
- next();
- };
- const checkProp = (predicate, prop) => obj => !!predicate(obj[prop]);
- 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 compactWhitespace = str => str.replace(/\s{2,}/g, ' ');
- 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 createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
- 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);
- if (this.hub[event].length === 0) delete this.hub[event];
- }
- });
- 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 => {
- if (obj === null) return null;
- 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) && obj.length
- ? (clone.length = obj.length) && Array.from(clone)
- : Array.isArray(obj)
- ? Array.from(obj)
- : 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 deepGet = (obj, keys) => keys.reduce((xs, x) => (xs && xs[x] ? xs[x] : null), obj);
- const deepMapKeys = (obj, f) =>
- Array.isArray(obj)
- ? obj.map(val => deepMapKeys(val, f))
- : typeof obj === 'object'
- ? Object.keys(obj).reduce((acc, current) => {
- const val = obj[current];
- acc[f(current)] =
- val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);
- return acc;
- }, {})
- : 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.map(fn).filter(el => !s.has(el));
- };
- 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) => {
- let rightIndex = arr.length;
- while (rightIndex-- && !func(arr[rightIndex]));
- return arr.slice(0, rightIndex + 1);
- };
- 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.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 filterFalsy = arr => arr.filter(Boolean);
- 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() || [-1])[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 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 formToObject = form =>
- Array.from(new FormData(form)).reduce(
- (acc, [key, value]) => ({
- ...acc,
- [key]: value
- }),
- {}
- );
- 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 frequencies = arr =>
- arr.reduce((a, v) => {
- a[v] = a[v] ? a[v] + 1 : 1;
- return a;
- }, {});
- 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 hasKey = (obj, keys) => {
- return (
- keys.length > 0 &&
- keys.every(key => {
- if (typeof obj !== 'object' || !obj.hasOwnProperty(key)) return false;
- obj = obj[key];
- return true;
- })
- );
- };
- const haveSameContents = (a, b) => {
- for (const v of new Set([...a, ...b]))
- if (a.filter(e => e === v).length !== b.filter(e => e === v).length) return false;
- return true;
- };
- const head = arr => (arr && arr.length ? arr[0] : undefined);
- 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 = (...el) => [...el].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 includesAll = (arr, values) => values.every(v => arr.includes(v));
- const includesAny = (arr, values) => values.some(v => arr.includes(v));
- 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 isContainedIn = (a, b) => {
- for (const v of new Set(a)) {
- if (!b.some(e => e === v) || a.filter(e => e === v).length > b.filter(e => e === v).length)
- return false;
- }
- return true;
- };
- 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 isNegativeZero = val => val === 0 && 1 / val === -Infinity;
- const isNil = val => val === undefined || val === null;
- const isNull = val => val === null;
- const isNumber = val => typeof val === 'number' && val === val;
- const isObject = obj => obj === Object(obj);
- const isObjectLike = val => val !== null && typeof val === 'object';
- const isOdd = num => num % 2 === 1;
- const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;
- const isPowerOfTwo = n => !!n && (n & (n - 1)) == 0;
- 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 = str => {
- try {
- JSON.parse(str);
- return true;
- } catch (e) {
- return false;
- }
- };
- const isWeekday = (t = new Date()) => {
- return t.getDay() % 6 !== 0;
- };
- const isWeekend = (t = new Date()) => {
- return t.getDay() % 6 === 0;
- };
- 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 ? arr[arr.length - 1] : undefined);
- 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 = (...vals) => 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 ? val * 2 - 9 : val * 2)), 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 mapNumRange = (num, inMin, inMax, outMin, outMax) =>
- ((num - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
- 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(...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 midpoint = ([x1, y1], [x2, y2]) => [(x1 + x2) / 2, (y1 + y2) / 2];
- const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn]));
- const minDate = dates => new Date(Math.min(...dates));
- const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
- const mostFrequent = arr =>
- Object.entries(
- arr.reduce((a, v) => {
- a[v] = a[v] ? a[v] + 1 : 1;
- return a;
- }, {})
- ).reduce((a, v) => (v[1] >= a[1] ? v : a), [null, 0])[0];
- 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 objectToQueryString = queryParameters => {
- return queryParameters
- ? Object.entries(queryParameters).reduce((queryString, [key, val], index) => {
- const symbol = queryString.length === 0 ? '?' : '&';
- queryString += typeof val === 'string' ? `${symbol}${key}=${val}` : '';
- return queryString;
- }, '')
- : '';
- };
- 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 => !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 serializeForm = form =>
- Array.from(new FormData(form), field => field.map(encodeURIComponent).join('=')).join('&');
- 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 = () => {
- let t = new Date();
- t.setDate(t.getDate() + 1);
- return t.toISOString().split('T')[0];
- };
- 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 toTitleCase = 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.charAt(0).toUpperCase() + x.slice(1))
- .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 vectorDistance = (...coords) => {
- let pointLength = Math.trunc(coords.length / 2);
- let sum = coords
- .slice(0, pointLength)
- .reduce((acc, val, i) => acc + Math.pow(val - coords[pointLength + i], 2), 0);
- return Math.sqrt(sum);
- };
- const weightedSample = (arr, weights) => {
- let roll = Math.random();
- return arr[
- weights
- .reduce((acc, w, i) => (i === 0 ? [w] : [...acc, acc[acc.length - 1] + w]), [])
- .findIndex((v, i, s) => roll >= (i === 0 ? 0 : s[i - 1]) && roll < v)
- ];
- };
- 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 yesterday = () => {
- let t = new Date();
- t.setDate(t.getDate() - 1);
- return t.toISOString().split('T')[0];
- };
- 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 binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
- if (start > end) return -1;
- const mid = Math.floor((start + end) / 2);
- if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);
- 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) {
- cleanObj(obj[key], keysToKeep, childIndicator);
- } else if (!keysToKeep.includes(key)) {
- delete obj[key];
- }
- });
- return obj;
- };
- const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);
- const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
- const factors = (num, primes = false) => {
- const isPrime = num => {
- const boundary = Math.floor(Math.sqrt(num));
- for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
- return num >= 2;
- };
- const isNeg = num < 0;
- num = isNeg ? -num : num;
- let array = Array.from({ length: num - 1 })
- .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))
- .filter(val => val);
- if (isNeg)
- array = array.reduce((acc, val) => {
- acc.push(val);
- acc.push(-val);
- return acc;
- }, []);
- return primes ? array.filter(isPrime) : array;
- };
- const 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 => {
- let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
- return Array.from({ length: n }).reduce(
- (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
- []
- );
- };
- const heronArea = (side_a, side_b, side_c) => {
- const p = (side_a + side_b + side_c) / 2;
- return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))
- };
- const howManyTimes = (num, divisor) => {
- if (divisor === 1 || divisor === -1) return Infinity;
- if (divisor === 0) return 0;
- let i = 0;
- while (Number.isInteger(num / divisor)) {
- i++;
- num = num / divisor;
- }
- return i;
- };
- const httpDelete = (url, callback, err = console.error) => {
- const request = new XMLHttpRequest();
- request.open('DELETE', url, true);
- request.onload = () => callback(request);
- request.onerror = () => err(request);
- request.send();
- };
- const httpPut = (url, data, callback, err = console.error) => {
- const request = new XMLHttpRequest();
- request.open("PUT", url, true);
- request.setRequestHeader('Content-type','application/json; charset=utf-8');
- request.onload = () => callback(request);
- request.onerror = () => err(request);
- request.send(data);
- };
- const isArmstrongNumber = digits =>
- (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
- (digits + '').split('')
- );
- const isSimilar = (pattern, str) =>
- [...str].reduce(
- (matchIndex, char) =>
- char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase()
- ? matchIndex + 1
- : matchIndex,
- 0
- ) === pattern.length;
- const JSONToDate = arr => {
- 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;
- let matrix = Array(string2.length + 1)
- .fill(0)
- .map((x, i) => [i]);
- matrix[0] = Array(string1.length + 1)
- .fill(0)
- .map((x, i) => i);
- for (let i = 1; i <= string2.length; i++) {
- for (let j = 1; j <= string1.length; j++) {
- if (string2[i - 1] === string1[j - 1]) {
- matrix[i][j] = matrix[i - 1][j - 1];
- } else {
- matrix[i][j] = Math.min(
- matrix[i - 1][j - 1] + 1,
- matrix[i][j - 1] + 1,
- matrix[i - 1][j] + 1
- );
- }
- }
- }
- 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)
- ? []
- : [
- ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),
- n,
- ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)
- ];
- const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);
- const solveRPN = rpn => {
- const OPERATORS = {
- '*': (a, b) => a * b,
- '+': (a, b) => a + b,
- '-': (a, b) => a - b,
- '/': (a, b) => a / b,
- '**': (a, b) => a ** b
- };
- const [stack, solve] = [
- [],
- rpn
- .replace(/\^/g, '**')
- .split(/\s+/g)
- .filter(el => !/\s+/.test(el) && el !== '')
- ];
- solve.forEach(symbol => {
- if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {
- stack.push(symbol);
- } else if (Object.keys(OPERATORS).includes(symbol)) {
- const [a, b] = [stack.pop(), stack.pop()];
- stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));
- } else {
- throw `${symbol} is not a recognized symbol`;
- }
- });
- if (stack.length === 1) return stack.pop();
- else throw `${rpn} is not a proper RPN. Please check it and try again`;
- };
- const speechSynthesis = message => {
- const msg = new SpeechSynthesisUtterance(message);
- msg.voice = window.speechSynthesis.getVoices()[0];
- window.speechSynthesis.speak(msg);
- };
- const squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0);
-
- 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.checkProp = checkProp;
- 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.compactWhitespace = compactWhitespace;
- exports.compose = compose;
- exports.composeRight = composeRight;
- exports.converge = converge;
- exports.copyToClipboard = copyToClipboard;
- exports.countBy = countBy;
- exports.counter = counter;
- exports.countOccurrences = countOccurrences;
- exports.createDirIfNotExists = createDirIfNotExists;
- exports.createElement = createElement;
- exports.createEventHub = createEventHub;
- exports.CSVToArray = CSVToArray;
- exports.CSVToJSON = CSVToJSON;
- 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.deepGet = deepGet;
- exports.deepMapKeys = deepMapKeys;
- 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.filterFalsy = filterFalsy;
- 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.formatDuration = formatDuration;
- exports.formToObject = formToObject;
- exports.forOwn = forOwn;
- exports.forOwnRight = forOwnRight;
- exports.frequencies = frequencies;
- 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.hasKey = hasKey;
- exports.haveSameContents = haveSameContents;
- exports.head = head;
- exports.hexToRGB = hexToRGB;
- exports.hide = hide;
- exports.httpGet = httpGet;
- exports.httpPost = httpPost;
- exports.httpsRedirect = httpsRedirect;
- exports.hz = hz;
- exports.includesAll = includesAll;
- exports.includesAny = includesAny;
- 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.inRange = inRange;
- 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.isContainedIn = isContainedIn;
- exports.isDivisible = isDivisible;
- exports.isDuplexStream = isDuplexStream;
- exports.isEmpty = isEmpty;
- exports.isEven = isEven;
- exports.isFunction = isFunction;
- exports.isLowerCase = isLowerCase;
- exports.isNegativeZero = isNegativeZero;
- exports.isNil = isNil;
- exports.isNull = isNull;
- exports.isNumber = isNumber;
- exports.isObject = isObject;
- exports.isObjectLike = isObjectLike;
- exports.isOdd = isOdd;
- exports.isPlainObject = isPlainObject;
- exports.isPowerOfTwo = isPowerOfTwo;
- 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.isWeekday = isWeekday;
- exports.isWeekend = isWeekend;
- exports.isWritableStream = isWritableStream;
- exports.join = join;
- exports.JSONtoCSV = JSONtoCSV;
- exports.JSONToFile = JSONToFile;
- exports.last = last;
- exports.lcm = lcm;
- exports.longestItem = longestItem;
- exports.lowercaseKeys = lowercaseKeys;
- exports.luhnCheck = luhnCheck;
- exports.mapKeys = mapKeys;
- exports.mapNumRange = mapNumRange;
- 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.midpoint = midpoint;
- exports.minBy = minBy;
- exports.minDate = minDate;
- exports.minN = minN;
- exports.mostFrequent = mostFrequent;
- 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.objectToQueryString = objectToQueryString;
- exports.observeMutations = observeMutations;
- exports.off = off;
- exports.offset = offset;
- exports.omit = omit;
- exports.omitBy = omitBy;
- exports.on = on;
- exports.once = once;
- exports.onUserInputChange = onUserInputChange;
- 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.reducedFilter = reducedFilter;
- exports.reduceSuccessive = reduceSuccessive;
- exports.reduceWhich = reduceWhich;
- exports.reject = reject;
- exports.remove = remove;
- exports.removeNonASCII = removeNonASCII;
- exports.renameKeys = renameKeys;
- exports.reverseString = reverseString;
- exports.RGBToHex = RGBToHex;
- 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.serializeForm = serializeForm;
- 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.times = times;
- exports.timeTaken = timeTaken;
- exports.toCamelCase = toCamelCase;
- exports.toCurrency = toCurrency;
- exports.toDecimalMark = toDecimalMark;
- exports.toggleClass = toggleClass;
- exports.toHash = toHash;
- exports.toKebabCase = toKebabCase;
- exports.tomorrow = tomorrow;
- exports.toOrdinalSuffix = toOrdinalSuffix;
- exports.toSafeInteger = toSafeInteger;
- exports.toSnakeCase = toSnakeCase;
- exports.toTitleCase = toTitleCase;
- 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.URLJoin = URLJoin;
- exports.UUIDGeneratorBrowser = UUIDGeneratorBrowser;
- exports.UUIDGeneratorNode = UUIDGeneratorNode;
- exports.validateNumber = validateNumber;
- exports.vectorDistance = vectorDistance;
- exports.weightedSample = weightedSample;
- exports.when = when;
- exports.without = without;
- exports.words = words;
- exports.xProd = xProd;
- exports.yesNo = yesNo;
- exports.yesterday = yesterday;
- exports.zip = zip;
- exports.zipObject = zipObject;
- exports.zipWith = zipWith;
- exports.binarySearch = binarySearch;
- exports.celsiusToFahrenheit = celsiusToFahrenheit;
- exports.cleanObj = cleanObj;
- exports.collatz = collatz;
- exports.countVowels = countVowels;
- exports.factors = factors;
- exports.fahrenheitToCelsius = fahrenheitToCelsius;
- exports.fibonacciCountUntilNum = fibonacciCountUntilNum;
- exports.fibonacciUntilNum = fibonacciUntilNum;
- exports.heronArea = heronArea;
- exports.howManyTimes = howManyTimes;
- exports.httpDelete = httpDelete;
- exports.httpPut = httpPut;
- exports.isArmstrongNumber = isArmstrongNumber;
- exports.isSimilar = isSimilar;
- exports.JSONToDate = JSONToDate;
- exports.kmphToMph = kmphToMph;
- exports.levenshteinDistance = levenshteinDistance;
- exports.mphToKmph = mphToKmph;
- exports.pipeLog = pipeLog;
- exports.quickSort = quickSort;
- exports.removeVowels = removeVowels;
- exports.solveRPN = solveRPN;
- exports.speechSynthesis = speechSynthesis;
- exports.squareSum = squareSum;
-
- Object.defineProperty(exports, '__esModule', { value: true });
-
-})));
diff --git a/package.json b/package.json
index 330c0e742..3c2ad606b 100644
--- a/package.json
+++ b/package.json
@@ -7,10 +7,7 @@
"sideEffects": false,
"scripts": {
"linter": "node ./scripts/lint.js",
- "extractor": "extract-snippet-data config.js",
- "vscoder": "node ./scripts/vscodegen.js",
- "packager": "node ./scripts/module.js",
- "test": "jest --verbose --coverage --testPathIgnorePatterns=\".cache\""
+ "extractor": "extract-snippet-data config.js"
},
"repository": {
"type": "git",
@@ -30,20 +27,9 @@
"dependencies": {},
"devDependencies": {
"@30-seconds/integration-tools": "^1.3.4",
- "@babel/core": "^7.5.4",
- "@babel/plugin-proposal-class-properties": "^7.5.0",
- "@babel/plugin-syntax-dynamic-import": "^7.2.0",
- "@babel/preset-env": "^7.5.4",
- "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
- "babel-plugin-transform-object-rest-spread": "^6.26.0",
"eslint": "^5.16.0",
- "front-matter": "^3.0.2",
"fs-extra": "^8.1.0",
- "jest": "^24.9.0",
"kleur": "^3.0.3",
- "prettier": "^1.18.2",
- "rollup": "^0.58.2",
- "rollup-plugin-babel": "^4.0.3",
- "rollup-plugin-babel-minify": "^4.0.0"
+ "prettier": "^1.18.2"
}
}
diff --git a/scripts/lint.js b/scripts/lint.js
index bf1b18a06..bce7e5803 100644
--- a/scripts/lint.js
+++ b/scripts/lint.js
@@ -9,8 +9,8 @@ const fs = require('fs-extra');
const cp = require('child_process');
const path = require('path');
const { green, red } = require('kleur');
-const util = require('./util');
-if (util.isTravisCI() && /^Travis build: \d+/g.test(process.env['TRAVIS_COMMIT_MESSAGE'])) {
+const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
+if (isTravisCI() && /^Travis build: \d+/g.test(process.env['TRAVIS_COMMIT_MESSAGE'])) {
console.log(`${green('NOBUILD')} Linting terminated, parent commit is a Travis build!`);
process.exit(0);
}
diff --git a/scripts/module.js b/scripts/module.js
deleted file mode 100644
index c3f6440e6..000000000
--- a/scripts/module.js
+++ /dev/null
@@ -1,144 +0,0 @@
-/**
- * Builds the `_30s` module in UMD and ESM formats.
- * Also builds the test module file for testing snippets.
- */
-const fs = require('fs-extra');
-const path = require('path');
-const { green, red } = require('kleur');
-const util = require('./util');
-const { rollup } = require('rollup');
-const babel = require('rollup-plugin-babel');
-const minify = require('rollup-plugin-babel-minify');
-const config = require('../config');
-
-const MODULE_NAME = `./${config.moduleName}`;
-const SNIPPETS_PATH = `./${config.snippetPath}`;
-const SNIPPETS_ARCHIVE_PATH = `./${config.snippetArchivePath}`;
-const DIST_PATH = `./${config.distPath}`;
-const ROLLUP_INPUT_FILE = `./${config.rollupInputFile}`;
-const TEST_MODULE_FILE = `./${config.testModuleFile}`;
-const CODE_RE = /```\s*js([\s\S]*?)```/;
-
-/**
- * Builds the UMD + ESM files to the ./dist directory.
- */
-async function doRollup() {
- // Plugins
- const es5 = babel({ presets: ['@babel/preset-env'], plugins: ['transform-object-rest-spread'] });
- const min = minify({ comments: false });
-
- const output = format => file => ({
- format,
- file,
- name: MODULE_NAME
- });
-
- const umd = output('umd');
- const esm = output('es');
-
- const bundle = await rollup({ input: ROLLUP_INPUT_FILE });
- const bundleES5 = await rollup({ input: ROLLUP_INPUT_FILE, plugins: [es5] });
- const bundleES5Min = await rollup({
- input: ROLLUP_INPUT_FILE,
- plugins: [es5, min]
- });
-
- const baseName = `${DIST_PATH}/${MODULE_NAME}`;
-
- // UMD ES2018
- await bundle.write(umd(`${baseName}.js`));
- // ESM ES2018
- await bundle.write(esm(`${baseName}.esm.js`));
- // UMD ES5
- await bundleES5.write(umd(`${baseName}.es5.js`));
- // UMD ES5 min
- await bundleES5Min.write(umd(`${baseName}.es5.min.js`));
-}
-
-/**
- * Starts the build process.
- */
-async function build() {
- console.time('Packager');
-
- let requires = [];
- let esmExportString = '';
- let cjsExportString = '';
-
- try {
- if (!fs.existsSync(DIST_PATH)) fs.mkdirSync(DIST_PATH);
- fs.writeFileSync(ROLLUP_INPUT_FILE, '');
- fs.writeFileSync(TEST_MODULE_FILE, '');
-
- // Synchronously read all snippets from snippets folder and sort them as necessary (case-insensitive)
- snippets = util.readSnippets(SNIPPETS_PATH);
- snippetsArray = Object.keys(snippets).reduce((acc, key) => {
- acc.push(snippets[key]);
- return acc;
- }, []);
- archivedSnippets = util.readSnippets(SNIPPETS_ARCHIVE_PATH);
- archivedSnippetsArray = Object.keys(archivedSnippets).reduce((acc, key) => {
- acc.push(archivedSnippets[key]);
- return acc;
- }, []);
-
- [...snippetsArray, ...archivedSnippetsArray].forEach(snippet => {
- let code = `${snippet.attributes.codeBlocks.es6}\n`;
- if(snippet.attributes.tags.includes('node')) {
- requires.push(code.match(/const.*=.*require\(([^\)]*)\);/g));
- code = code.replace(/const.*=.*require\(([^\)]*)\);/g, '');
- }
- esmExportString += `export ${code}`;
- cjsExportString += code;
- });
-
- requires = [
- ...new Set(
- requires
- .filter(Boolean)
- .map(v =>
- v[0].replace(
- 'require(',
- 'typeof require !== "undefined" && require('
- )
- )
- )
- ].join('\n');
-
- fs.writeFileSync(ROLLUP_INPUT_FILE, `${requires}\n\n${esmExportString}`);
-
- const testExports = `module.exports = {${[...snippetsArray, ...archivedSnippetsArray]
- .map(v => v.id)
- .join(',')}}`;
-
- fs.writeFileSync(
- TEST_MODULE_FILE,
- `${requires}\n\n${cjsExportString}\n\n${testExports}`
- );
-
- // Check Travis builds - Will skip builds on Travis if not CRON/API
- if (util.isTravisCI() && util.isNotTravisCronOrAPI()) {
- fs.unlink(ROLLUP_INPUT_FILE);
- console.log(
- `${green(
- 'NOBUILD'
- )} Module build terminated, not a cron job or a custom build!`
- );
- console.timeEnd('Packager');
- process.exit(0);
- }
-
- await doRollup();
-
- // Clean up the temporary input file Rollup used for building the module
- fs.unlink(ROLLUP_INPUT_FILE);
-
- console.log(`${green('SUCCESS!')} Snippet module built!`);
- console.timeEnd('Packager');
- } catch (err) {
- console.log(`${red('ERROR!')} During module creation: ${err}`);
- process.exit(1);
- }
-}
-
-build();
diff --git a/scripts/util/environmentCheck.js b/scripts/util/environmentCheck.js
deleted file mode 100644
index 05c441bb9..000000000
--- a/scripts/util/environmentCheck.js
+++ /dev/null
@@ -1,12 +0,0 @@
-// Checks if current environment is Travis CI, Cron builds, API builds
-const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
-const isTravisCronOrAPI = () =>
- process.env['TRAVIS_EVENT_TYPE'] === 'cron' ||
- process.env['TRAVIS_EVENT_TYPE'] === 'api';
-const isNotTravisCronOrAPI = () => !isTravisCronOrAPI();
-
-module.exports = {
- isTravisCI,
- isTravisCronOrAPI,
- isNotTravisCronOrAPI,
-};
diff --git a/scripts/util/helpers.js b/scripts/util/helpers.js
deleted file mode 100644
index a2057a81a..000000000
--- a/scripts/util/helpers.js
+++ /dev/null
@@ -1,60 +0,0 @@
-const config = require('../../config');
-
-const getMarkDownAnchor = paragraphTitle =>
- paragraphTitle
- .trim()
- .toLowerCase()
- .replace(/[^\w\- ]+/g, '')
- .replace(/\s/g, '-')
- .replace(/\-+$/, '');
-// Creates an object from pairs
-const objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {});
-// Optimizes nodes in an HTML document
-const optimizeNodes = (data, regexp, replacer) => {
- let count = 0;
- let output = data;
- do {
- output = output.replace(regexp, replacer);
- count = 0;
- while (regexp.exec(output) !== null) ++count;
- } while (count > 0);
- return output;
-};
-// Capitalizes the first letter of a string
-const capitalize = (str, lowerRest = false) =>
- str.slice(0, 1).toUpperCase() +
- (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
-const prepTaggedData = tagDbData =>
- [...new Set(Object.entries(tagDbData).map(t => t[1][0]))]
- .filter(v => v)
- .sort((a, b) =>
- capitalize(a, true) === 'Uncategorized'
- ? 1
- : capitalize(b, true) === 'Uncategorized'
- ? -1
- : a.localeCompare(b),
- );
-const makeExamples = data => {
- data =
- data.slice(0, data.lastIndexOf(`\`\`\`${config.language.short}`)).trim() +
- misc.collapsible(
- 'Examples',
- data.slice(
- data.lastIndexOf(`\`\`\`${config.language.short}`),
- data.lastIndexOf('```'),
- ) + data.slice(data.lastIndexOf('```')),
- );
- return `${data}\n
${misc.link(
- '⬆ Back to top',
- misc.anchor('Contents'),
- )}\n\n`;
-};
-
-module.exports = {
- getMarkDownAnchor,
- objectFromPairs,
- optimizeNodes,
- capitalize,
- prepTaggedData,
- makeExamples,
-};
diff --git a/scripts/util/index.js b/scripts/util/index.js
deleted file mode 100644
index 27edbfec9..000000000
--- a/scripts/util/index.js
+++ /dev/null
@@ -1,37 +0,0 @@
-const {
- isTravisCI,
- isTravisCronOrAPI,
- isNotTravisCronOrAPI,
-} = require('./environmentCheck');
-const {
- getMarkDownAnchor,
- objectFromPairs,
- optimizeNodes,
- capitalize,
- prepTaggedData,
- makeExamples,
-} = require('./helpers');
-const {
- getFilesInDir,
- hashData,
- getCodeBlocks,
- getTextualContent,
- readSnippets,
-} = require('./snippetParser');
-
-module.exports = {
- isTravisCI,
- isTravisCronOrAPI,
- isNotTravisCronOrAPI,
- getMarkDownAnchor,
- objectFromPairs,
- optimizeNodes,
- capitalize,
- prepTaggedData,
- makeExamples,
- getFilesInDir,
- hashData,
- getCodeBlocks,
- getTextualContent,
- readSnippets,
-};
diff --git a/scripts/util/snippetParser.js b/scripts/util/snippetParser.js
deleted file mode 100644
index d0c8d8c59..000000000
--- a/scripts/util/snippetParser.js
+++ /dev/null
@@ -1,125 +0,0 @@
-const fs = require('fs-extra'),
- path = require('path'),
- { red } = require('kleur'),
- crypto = require('crypto'),
- frontmatter = require('front-matter'),
- babel = require('@babel/core');
-const config = require('../../config');
-const execSync = require('child_process').execSync;
-
-// Reade all files in a directory
-const getFilesInDir = (directoryPath, withPath, exclude = null) => {
- try {
- let directoryFilenames = fs.readdirSync(directoryPath);
- directoryFilenames.sort((a, b) => {
- a = a.toLowerCase();
- b = b.toLowerCase();
- if (a < b) return -1;
- if (a > b) return 1;
- return 0;
- });
-
- if (withPath) {
- // a hacky way to do conditional array.map
- return directoryFilenames.reduce((fileNames, fileName) => {
- if (
- exclude == null ||
- !exclude.some(toExclude => fileName === toExclude)
- )
- fileNames.push(`${directoryPath}/${fileName}`);
- return fileNames;
- }, []);
- }
- return directoryFilenames.filter(v => v !== 'README.md');
- } catch (err) {
- console.log(`${red('ERROR!')} During snippet loading: ${err}`);
- process.exit(1);
- }
-};
-// Creates a hash for a value using the SHA-256 algorithm.
-const hashData = val =>
- crypto
- .createHash('sha256')
- .update(val)
- .digest('hex');
-// Gets the code blocks for a snippet file.
-const getCodeBlocks = str => {
- const regex = /```[.\S\s]*?```/g;
- let results = [];
- let m = null;
- while ((m = regex.exec(str)) !== null) {
- if (m.index === regex.lastIndex) regex.lastIndex += 1;
-
- m.forEach((match, groupIndex) => {
- results.push(match);
- });
- }
- const replacer = new RegExp(
- `\`\`\`${config.language.short}([\\s\\S]*?)\`\`\``,
- 'g',
- );
- results = results.map(v => v.replace(replacer, '$1').trim());
- return {
- es6: results[0],
- es5: babel.transformSync(results[0], { presets: ['@babel/preset-env'] }).code.replace('"use strict";\n\n', ''),
- example: results[1],
- };
-};
-// Gets the textual content for a snippet file.
-const getTextualContent = str => {
- const regex = /([\s\S]*?)```/g;
- const results = [];
- let m = null;
- while ((m = regex.exec(str)) !== null) {
- if (m.index === regex.lastIndex) regex.lastIndex += 1;
-
- m.forEach((match, groupIndex) => {
- results.push(match);
- });
- }
- if (!results.length) return str.replace(/\r\n/g, '\n');
- return results[1].replace(/\r\n/g, '\n');
-};
-
-// Synchronously read all snippets and sort them as necessary (case-insensitive)
-const readSnippets = snippetsPath => {
- const snippetFilenames = getFilesInDir(snippetsPath, false);
-
- let snippets = {};
- try {
- for (let snippet of snippetFilenames) {
- let data = frontmatter(
- fs.readFileSync(path.join(snippetsPath, snippet), 'utf8'),
- );
- snippets[snippet] = {
- id: snippet.slice(0, -3),
- title: data.attributes.title,
- type: 'snippet',
- attributes: {
- fileName: snippet,
- text: getTextualContent(data.body),
- codeBlocks: getCodeBlocks(data.body),
- tags: data.attributes.tags.split(',').map(t => t.trim()),
- },
- meta: {
- hash: hashData(data.body),
- firstSeen: execSync(`git log --diff-filter=A --pretty=format:%at -- snippets/${snippet}`).toString(),
- lastUpdated: execSync(`git log -n 1 --pretty=format:%at -- snippets/${snippet}`).toString(),
- updateCount: execSync(`git log --pretty=%H -- snippets/${snippet}`).toString().split('\n').length
- },
- };
- }
- } catch (err) {
- console.log(`${red('ERROR!')} During snippet loading: ${err}`);
- process.exit(1);
- }
- return snippets;
-};
-
-module.exports = {
- getFilesInDir,
- hashData,
- getCodeBlocks,
- getTextualContent,
- readSnippets
-};
diff --git a/scripts/vscodegen.js b/scripts/vscodegen.js
deleted file mode 100644
index 458c81893..000000000
--- a/scripts/vscodegen.js
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- This is the VSCode generator script that generates the vscode_snippets/snippets.json file.
- Run using `npm run vscoder`.
-*/
-// Load modules
-const fs = require('fs-extra');
-const path = require('path');
-const { green } = require('kleur');
-let snippetsData = require('../snippet_data/snippets.json');
-// Paths
-const OUTPUT_PATH = './vscode_snippets';
-console.time('VSCoder');
-// Read and format data
-let vscodeData = snippetsData.data.filter(v => !v.meta.archived ).reduce((acc, v) => {
- acc[v.id] = {
- prefix: `30s_${v.id}`,
- body: v.attributes.codeBlocks.es6.replace(/\r/g, '').split('\n'),
- description: v.attributes.text.slice(0, v.attributes.text.indexOf('\r\n\r\n'))
- };
- return acc;
-}, {});
-// Write data
-fs.writeFileSync(
- path.join(OUTPUT_PATH, 'snippets.json'),
- JSON.stringify(vscodeData, null, 2)
-);
-// Display messages and time
-console.log(
- `${green(
- 'SUCCESS!'
- )} vscode_snippets/snippets.json file generated!`
-);
-console.timeEnd('VSCoder');
diff --git a/snippet_data/archivedSnippetList.json b/snippet_data/archivedSnippetList.json
deleted file mode 100644
index f8f03cfab..000000000
--- a/snippet_data/archivedSnippetList.json
+++ /dev/null
@@ -1,406 +0,0 @@
-{
- "data": [
- {
- "id": "binarySearch",
- "type": "snippetListing",
- "title": "binarySearch",
- "attributes": {
- "text": "Use recursion. Similar to `Array.prototype.indexOf()` that finds the index of a value within an array.\nThe difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or `Array.prototype.indexOf()`.\n\nSearch a sorted array by repeatedly dividing the search interval in half.\nBegin with an interval covering the whole array.\nIf the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half.\nRepeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return `-1`.\n\n",
- "tags": [
- "algorithm",
- "beginner"
- ]
- },
- "meta": {
- "hash": "48d538bccbc7be7e78b8f6a69004055c4b21324d2c8d7cbc4cba0cd42e4f67fb"
- }
- },
- {
- "id": "celsiusToFahrenheit",
- "type": "snippetListing",
- "title": "celsiusToFahrenheit",
- "attributes": {
- "text": "Celsius to Fahrenheit temperature conversion.\n\nFollows the conversion formula `F = 1.8C + 32`.\n\n",
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "d59410c4fa0ea5173af553068c1e1d4ef931695e084c50cdd8166b0cd0278722"
- }
- },
- {
- "id": "cleanObj",
- "type": "snippetListing",
- "title": "cleanObj",
- "attributes": {
- "text": "Removes any properties except the ones specified from a JSON object.\n\nUse `Object.keys()` method to loop over given JSON object and deleting keys that are not included in given array.\nIf you pass a special key,`childIndicator`, it will search deeply apply the function to inner objects, too.\n\n",
- "tags": [
- "object",
- "beginner"
- ]
- },
- "meta": {
- "hash": "aaefc9bd6e9170001fe4754b1bc7bb9808ab97a5bec7fc6ceb1193be2f8009b1"
- }
- },
- {
- "id": "collatz",
- "type": "snippetListing",
- "title": "collatz",
- "attributes": {
- "text": "Applies the Collatz algorithm.\n\nIf `n` is even, return `n/2`. Otherwise, return `3n+1`.\n\n",
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "0280a47e49f505d5f10e0e0bd2c3ab28a6ea2b931fc83f63155f8395f64a1840"
- }
- },
- {
- "id": "countVowels",
- "type": "snippetListing",
- "title": "countVowels",
- "attributes": {
- "text": "Returns `number` of vowels in provided string.\n\nUse a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`.\n\n",
- "tags": [
- "string",
- "beginner"
- ]
- },
- "meta": {
- "hash": "dbc7e4369d07c299fb69df1142c0c209fead5e159574de6144bff614848ec1c5"
- }
- },
- {
- "id": "factors",
- "type": "snippetListing",
- "title": "factors",
- "attributes": {
- "text": "Returns the array of factors of the given `num`.\nIf the second argument is set to `true` returns only the prime factors of `num`.\nIf `num` is `1` or `0` returns an empty array.\nIf `num` is less than `0` returns all the factors of `-int` together with their additive inverses.\n\nUse `Array.from()`, `Array.prototype.map()` and `Array.prototype.filter()` to find all the factors of `num`.\nIf given `num` is negative, use `Array.prototype.reduce()` to add the additive inverses to the array.\nReturn all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.prototype.filter()`.\nOmit the second argument, `primes`, to return prime and non-prime factors by default.\n\n**Note**:- _Negative numbers are not considered prime._\n\n",
- "tags": [
- "math",
- "intermediate"
- ]
- },
- "meta": {
- "hash": "8eed39b1040d6472e2fd619abf744848d30f12eebffda2711966c616d474524f"
- }
- },
- {
- "id": "fahrenheitToCelsius",
- "type": "snippetListing",
- "title": "fahrenheitToCelsius",
- "attributes": {
- "text": "Fahrenheit to Celsius temperature conversion.\n\nFollows the conversion formula `C = (F - 32) * 5/9`.\n\n",
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "a39ade2ae05ad86443446b335dbc019e3ac734fe0c1a542d50b929c554040fc0"
- }
- },
- {
- "id": "fibonacciCountUntilNum",
- "type": "snippetListing",
- "title": "fibonacciCountUntilNum",
- "attributes": {
- "text": "Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive).\n\nUse a mathematical formula to calculate the number of fibonacci numbers until `num`.\n\n",
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "35488eb0f56b59035b56cc67fa0a5e1a970162ede4aafd97ebb2b4009c321c01"
- }
- },
- {
- "id": "fibonacciUntilNum",
- "type": "snippetListing",
- "title": "fibonacciUntilNum",
- "attributes": {
- "text": "Generates an array, containing the Fibonacci sequence, up until the nth term.\n\nCreate an empty array of the specific length, initializing the first two values (`0` and `1`).\nUse `Array.prototype.reduce()` to add values into the array, using the sum of the last two values, except for the first two.\nUses a mathematical formula to calculate the length of the array required.\n\n",
- "tags": [
- "math",
- "intermediate"
- ]
- },
- "meta": {
- "hash": "6ff845c13444a06569be548ce9e69900b7001516c44c315795f34b31e9baa833"
- }
- },
- {
- "id": "heronArea",
- "type": "snippetListing",
- "title": "heronArea",
- "attributes": {
- "text": "Returns the area of a triangle using only the 3 side lengths, Heron's formula. Assumes that the sides define a valid triangle. Does NOT assume it is a right triangle.\n\nMore information on what Heron's formula is and why it works available here: https://en.wikipedia.org/wiki/Heron%27s_formula.\n\nUses `Math.sqrt()` to find the square root of a value.\n\n",
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "d0be594ab377cbeb2910308610af5890b3468c06e7567cd0995a84d11aaccf47"
- }
- },
- {
- "id": "howManyTimes",
- "type": "snippetListing",
- "title": "howManyTimes",
- "attributes": {
- "text": "Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer.\nWorks for both negative and positive integers.\n\nIf `divisor` is `-1` or `1` return `Infinity`.\nIf `divisor` is `-0` or `0` return `0`.\nOtherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer.\nReturn the number of times the loop was executed, `i`.\n\n",
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "52ffa251dfc4e2bec7160a9066ef24a8c3047706e1ad2837f9d987cdf4d5f73e"
- }
- },
- {
- "id": "httpDelete",
- "type": "snippetListing",
- "title": "httpDelete",
- "attributes": {
- "text": "Makes a `DELETE` request to the passed URL.\n\nUse `XMLHttpRequest` web api to make a `delete` request to the given `url`.\nHandle the `onload` event, by running the provided `callback` function.\nHandle the `onerror` event, by running the provided `err` function.\nOmit the third argument, `err` to log the request to the console's error stream by default.\n\n",
- "tags": [
- "browser",
- "intermediate"
- ]
- },
- "meta": {
- "hash": "4fccb2abe966313a742d13965ee46cfd1094763a2697591eddb19c1c5af1db7e"
- }
- },
- {
- "id": "httpPut",
- "type": "snippetListing",
- "title": "httpPut",
- "attributes": {
- "text": "Makes a `PUT` request to the passed URL.\n\nUse `XMLHttpRequest` web api to make a `put` request to the given `url`.\nSet the value of an `HTTP` request header with `setRequestHeader` method.\nHandle the `onload` event, by running the provided `callback` function.\nHandle the `onerror` event, by running the provided `err` function.\nOmit the last argument, `err` to log the request to the console's error stream by default.\n\n",
- "tags": [
- "browser",
- "intermediate"
- ]
- },
- "meta": {
- "hash": "7eb4b1ffc1cbe28c10190bb82b7731ade2d79e78a5569bdee62af33a1020f2f5"
- }
- },
- {
- "id": "isArmstrongNumber",
- "type": "snippetListing",
- "title": "isArmstrongNumber",
- "attributes": {
- "text": "Checks if the given number is an Armstrong number or not.\n\nConvert the given number into an array of digits. Use the exponent operator (`**`) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`.\n\n",
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "71ebcdb61794d8222fcf447509d206ffb10dc8068072a88c6b587e21e76fc7f2"
- }
- },
- {
- "id": "isSimilar",
- "type": "snippetListing",
- "title": "isSimilar",
- "attributes": {
- "text": "Determines if the `pattern` matches with `str`.\n\nUse `String.toLowerCase()` to convert both strings to lowercase, then loop through `str` and determine if it contains all characters of `pattern` and in the correct order.\nAdapted from [here](https://github.com/forrestthewoods/lib_fts/blob/80f3f8c52db53428247e741b9efe2cde9667050c/code/fts_fuzzy_match.js#L18).\n\n",
- "tags": [
- "string",
- "intermediate"
- ]
- },
- "meta": {
- "hash": "250615cfc281e99014b97d054c722d3ba6aa4190ccf66dd719e530ec80aec3bd"
- }
- },
- {
- "id": "JSONToDate",
- "type": "snippetListing",
- "title": "JSONToDate",
- "attributes": {
- "text": "Converts a JSON object to a date.\n\nUse `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).\n\n",
- "tags": [
- "object",
- "date",
- "beginner"
- ]
- },
- "meta": {
- "hash": "33e1e304fead4088971a60d4da974d0e9380370560f383ddb1ddc14e628df18b"
- }
- },
- {
- "id": "kmphToMph",
- "type": "snippetListing",
- "title": "kmphToMph",
- "attributes": {
- "text": "Convert kilometers/hour to miles/hour.\n\nMultiply the constant of proportionality with the argument.\n\n",
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "f885a599e1185f8480445e1eb0c4a5cb8bf33948d7893f013dd4e8085478fe7a"
- }
- },
- {
- "id": "levenshteinDistance",
- "type": "snippetListing",
- "title": "levenshteinDistance",
- "attributes": {
- "text": "Calculates the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between two strings.\n\nCalculates the number of changes (substitutions, deletions or additions) required to convert `string1` to `string2`. \nCan also be used to compare two strings as shown in the second example.\n\n",
- "tags": [
- "algorithm",
- "advanced"
- ]
- },
- "meta": {
- "hash": "9f71509c5937cb68b65ef31893b1ad723ce6690e8ecd161707cb222ab67a475b"
- }
- },
- {
- "id": "mphToKmph",
- "type": "snippetListing",
- "title": "mphToKmph",
- "attributes": {
- "text": "Convert miles/hour to kilometers/hour.\n\nMultiply the constant of proportionality with the argument.\n\n",
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "d1ec7968c8f8c48642a3f91878db84330231bdf84bf74633dc0754456e951338"
- }
- },
- {
- "id": "objectToEntries",
- "type": "snippetListing",
- "title": "objectToEntries",
- "attributes": {
- "text": "Creates an array of key-value pair arrays from an object.\n\nUse `Object.keys()` and `Array.prototype.map()` to iterate over the object's keys and produce an array with key-value pairs.\n\n",
- "tags": [
- "object",
- "array",
- "beginner"
- ]
- },
- "meta": {
- "hash": "da5ab6a4f794f33d985d8a82794414b80913e63214a80d78c87bbda9638faa4f"
- }
- },
- {
- "id": "pipeLog",
- "type": "snippetListing",
- "title": "pipeLog",
- "attributes": {
- "text": "Logs a value and returns it.\n\nUse `console.log` to log the supplied value, combined with the `||` operator to return it.\n\n",
- "tags": [
- "utility",
- "beginner"
- ]
- },
- "meta": {
- "hash": "dba6fa36424c23d601c4e463463a5f23d32b51d8b058a6c5020d3b4098a65e51"
- }
- },
- {
- "id": "quickSort",
- "type": "snippetListing",
- "title": "quickSort",
- "attributes": {
- "text": "QuickSort an Array (ascending sort by default).\n\nUse recursion.\nUse `Array.prototype.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it.\nIf the parameter `desc` is truthy, return array sorts in descending order.\n\n",
- "tags": [
- "algorithm",
- "recursion",
- "beginner"
- ]
- },
- "meta": {
- "hash": "5c26069a02342eadd2c5ba2656a1b211da8f1a94da03c2cc31a5090be556d7b7"
- }
- },
- {
- "id": "removeVowels",
- "type": "snippetListing",
- "title": "removeVowels",
- "attributes": {
- "text": "Returns all the vowels in a `str` replaced by `repl`.\n\nUse `String.prototype.replace()` with a regexp to replace all vowels in `str`.\nOmot `repl` to use a default value of `''`.\n\n",
- "tags": [
- "string",
- "beginner"
- ]
- },
- "meta": {
- "hash": "5c6f8e292db8506568de362aa63890047f9d5a65d35143cfca1e27562642c414"
- }
- },
- {
- "id": "solveRPN",
- "type": "snippetListing",
- "title": "solveRPN",
- "attributes": {
- "text": "Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation).\nThrows appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators.\n\nUse a dictionary, `OPERATORS` to specify each operator's matching mathematical operation.\nUse `String.prototype.replace()` with a regular expression to replace `^` with `**`, `String.prototype.split()` to tokenize the string and `Array.prototype.filter()` to remove empty tokens.\nUse `Array.prototype.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression.\nNumeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations.\n\n",
- "tags": [
- "algorithm",
- "advanced"
- ]
- },
- "meta": {
- "hash": "0c37cf46586652fd20dfa9ca682d3635f01fe61c46864f9773f6b258e8f3b6f6"
- }
- },
- {
- "id": "speechSynthesis",
- "type": "snippetListing",
- "title": "speechSynthesis",
- "attributes": {
- "text": "Performs speech synthesis (experimental).\n\nUse `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech.\nUse `window.speechSynthesis.speak()` to play the message.\n\nLearn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance).\n\n",
- "tags": [
- "browser",
- "intermediate"
- ]
- },
- "meta": {
- "hash": "9859dbef05dc0398e825150b50fccfea370583cf6b807c00c9e83b769d2b51c0"
- }
- },
- {
- "id": "squareSum",
- "type": "snippetListing",
- "title": "squareSum",
- "attributes": {
- "text": "Squares each number in an array and then sums the results together.\n\nUse `Array.prototype.reduce()` in combination with `Math.pow()` to iterate over numbers and sum their squares into an accumulator.\n\n",
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "19837ac6714833e9c5fe698811e171cc2598f7b9405a4847b33b8d3b35debf8a"
- }
- }
- ],
- "meta": {
- "specification": "http://jsonapi.org/format/",
- "type": "snippetListingArray",
- "scope": "./snippets_archive",
- "language": {
- "short": "js",
- "long": "JavaScript"
- }
- }
-}
\ No newline at end of file
diff --git a/snippet_data/archivedSnippets.json b/snippet_data/archivedSnippets.json
deleted file mode 100644
index 958705a22..000000000
--- a/snippet_data/archivedSnippets.json
+++ /dev/null
@@ -1,666 +0,0 @@
-{
- "data": [
- {
- "id": "binarySearch",
- "title": "binarySearch",
- "type": "snippet",
- "attributes": {
- "fileName": "binarySearch.md",
- "text": "Use recursion. Similar to `Array.prototype.indexOf()` that finds the index of a value within an array.\nThe difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or `Array.prototype.indexOf()`.\n\nSearch a sorted array by repeatedly dividing the search interval in half.\nBegin with an interval covering the whole array.\nIf the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half.\nRepeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return `-1`.\n\n",
- "codeBlocks": {
- "es6": "const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {\n if (start > end) return -1;\n const mid = Math.floor((start + end) / 2);\n if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);\n if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);\n return mid;\n};",
- "es5": "var binarySearch = function binarySearch(arr, val) {\n var start = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;\n var end = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : arr.length - 1;\n if (start > end) return -1;\n var mid = Math.floor((start + end) / 2);\n if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);\n if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);\n return mid;\n};",
- "example": "binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2\nbinarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1"
- },
- "tags": [
- "algorithm",
- "beginner"
- ]
- },
- "meta": {
- "hash": "48d538bccbc7be7e78b8f6a69004055c4b21324d2c8d7cbc4cba0cd42e4f67fb",
- "firstSeen": "1515453617",
- "lastUpdated": "1565681352",
- "updateCount": 6,
- "authorCount": 3
- }
- },
- {
- "id": "celsiusToFahrenheit",
- "title": "celsiusToFahrenheit",
- "type": "snippet",
- "attributes": {
- "fileName": "celsiusToFahrenheit.md",
- "text": "Celsius to Fahrenheit temperature conversion.\n\nFollows the conversion formula `F = 1.8C + 32`.\n\n",
- "codeBlocks": {
- "es6": "const celsiusToFahrenheit = degrees => 1.8 * degrees + 32;",
- "es5": "var celsiusToFahrenheit = function celsiusToFahrenheit(degrees) {\n return 1.8 * degrees + 32;\n};",
- "example": "celsiusToFahrenheit(33) // 91.4"
- },
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "d59410c4fa0ea5173af553068c1e1d4ef931695e084c50cdd8166b0cd0278722",
- "firstSeen": "1539711071",
- "lastUpdated": "1565681352",
- "updateCount": 3,
- "authorCount": 2
- }
- },
- {
- "id": "cleanObj",
- "title": "cleanObj",
- "type": "snippet",
- "attributes": {
- "fileName": "cleanObj.md",
- "text": "Removes any properties except the ones specified from a JSON object.\n\nUse `Object.keys()` method to loop over given JSON object and deleting keys that are not included in given array.\nIf you pass a special key,`childIndicator`, it will search deeply apply the function to inner objects, too.\n\n",
- "codeBlocks": {
- "es6": "const cleanObj = (obj, keysToKeep = [], childIndicator) => {\n Object.keys(obj).forEach(key => {\n if (key === childIndicator) {\n cleanObj(obj[key], keysToKeep, childIndicator);\n } else if (!keysToKeep.includes(key)) {\n delete obj[key];\n }\n });\n return obj;\n};",
- "es5": "var cleanObj = function cleanObj(obj) {\n var keysToKeep = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n var childIndicator = arguments.length > 2 ? arguments[2] : undefined;\n Object.keys(obj).forEach(function (key) {\n if (key === childIndicator) {\n cleanObj(obj[key], keysToKeep, childIndicator);\n } else if (!keysToKeep.includes(key)) {\n delete obj[key];\n }\n });\n return obj;\n};",
- "example": "const testObj = { a: 1, b: 2, children: { a: 1, b: 2 } };\ncleanObj(testObj, ['a'], 'children'); // { a: 1, children : { a: 1}}"
- },
- "tags": [
- "object",
- "beginner"
- ]
- },
- "meta": {
- "hash": "aaefc9bd6e9170001fe4754b1bc7bb9808ab97a5bec7fc6ceb1193be2f8009b1",
- "firstSeen": "1516359948",
- "lastUpdated": "1565681352",
- "updateCount": 3,
- "authorCount": 2
- }
- },
- {
- "id": "collatz",
- "title": "collatz",
- "type": "snippet",
- "attributes": {
- "fileName": "collatz.md",
- "text": "Applies the Collatz algorithm.\n\nIf `n` is even, return `n/2`. Otherwise, return `3n+1`.\n\n",
- "codeBlocks": {
- "es6": "const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);",
- "es5": "var collatz = function collatz(n) {\n return n % 2 === 0 ? n / 2 : 3 * n + 1;\n};",
- "example": "collatz(8); // 4"
- },
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "0280a47e49f505d5f10e0e0bd2c3ab28a6ea2b931fc83f63155f8395f64a1840",
- "firstSeen": "1515162834",
- "lastUpdated": "1565681352",
- "updateCount": 4,
- "authorCount": 2
- }
- },
- {
- "id": "countVowels",
- "title": "countVowels",
- "type": "snippet",
- "attributes": {
- "fileName": "countVowels.md",
- "text": "Returns `number` of vowels in provided string.\n\nUse a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`.\n\n",
- "codeBlocks": {
- "es6": "const countVowels = str => (str.match(/[aeiou]/gi) || []).length;",
- "es5": "var countVowels = function countVowels(str) {\n return (str.match(/[aeiou]/gi) || []).length;\n};",
- "example": "countVowels('foobar'); // 3\ncountVowels('gym'); // 0"
- },
- "tags": [
- "string",
- "beginner"
- ]
- },
- "meta": {
- "hash": "dbc7e4369d07c299fb69df1142c0c209fead5e159574de6144bff614848ec1c5",
- "firstSeen": "1515500549",
- "lastUpdated": "1584841330",
- "updateCount": 4,
- "authorCount": 3
- }
- },
- {
- "id": "factors",
- "title": "factors",
- "type": "snippet",
- "attributes": {
- "fileName": "factors.md",
- "text": "Returns the array of factors of the given `num`.\nIf the second argument is set to `true` returns only the prime factors of `num`.\nIf `num` is `1` or `0` returns an empty array.\nIf `num` is less than `0` returns all the factors of `-int` together with their additive inverses.\n\nUse `Array.from()`, `Array.prototype.map()` and `Array.prototype.filter()` to find all the factors of `num`.\nIf given `num` is negative, use `Array.prototype.reduce()` to add the additive inverses to the array.\nReturn all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.prototype.filter()`.\nOmit the second argument, `primes`, to return prime and non-prime factors by default.\n\n**Note**:- _Negative numbers are not considered prime._\n\n",
- "codeBlocks": {
- "es6": "const factors = (num, primes = false) => {\n const isPrime = num => {\n const boundary = Math.floor(Math.sqrt(num));\n for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;\n return num >= 2;\n };\n const isNeg = num < 0;\n num = isNeg ? -num : num;\n let array = Array.from({ length: num - 1 })\n .map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))\n .filter(val => val);\n if (isNeg)\n array = array.reduce((acc, val) => {\n acc.push(val);\n acc.push(-val);\n return acc;\n }, []);\n return primes ? array.filter(isPrime) : array;\n};",
- "es5": "var factors = function factors(num) {\n var primes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n var isPrime = function isPrime(num) {\n var boundary = Math.floor(Math.sqrt(num));\n\n for (var i = 2; i <= boundary; i++) {\n if (num % i === 0) return false;\n }\n\n return num >= 2;\n };\n\n var isNeg = num < 0;\n num = isNeg ? -num : num;\n var array = Array.from({\n length: num - 1\n }).map(function (val, i) {\n return num % (i + 2) === 0 ? i + 2 : false;\n }).filter(function (val) {\n return val;\n });\n if (isNeg) array = array.reduce(function (acc, val) {\n acc.push(val);\n acc.push(-val);\n return acc;\n }, []);\n return primes ? array.filter(isPrime) : array;\n};",
- "example": "factors(12); // [2,3,4,6,12]\nfactors(12, true); // [2,3]\nfactors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]\nfactors(-12, true); // [2,3]"
- },
- "tags": [
- "math",
- "intermediate"
- ]
- },
- "meta": {
- "hash": "8eed39b1040d6472e2fd619abf744848d30f12eebffda2711966c616d474524f",
- "firstSeen": "1515162834",
- "lastUpdated": "1565681352",
- "updateCount": 4,
- "authorCount": 3
- }
- },
- {
- "id": "fahrenheitToCelsius",
- "title": "fahrenheitToCelsius",
- "type": "snippet",
- "attributes": {
- "fileName": "fahrenheitToCelsius.md",
- "text": "Fahrenheit to Celsius temperature conversion.\n\nFollows the conversion formula `C = (F - 32) * 5/9`.\n\n",
- "codeBlocks": {
- "es6": "const fahrenheitToCelsius = degrees => (degrees - 32) * 5/9;",
- "es5": "var fahrenheitToCelsius = function fahrenheitToCelsius(degrees) {\n return (degrees - 32) * 5 / 9;\n};",
- "example": "fahrenheitToCelsius(32); // 0"
- },
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "a39ade2ae05ad86443446b335dbc019e3ac734fe0c1a542d50b929c554040fc0",
- "firstSeen": "1539711071",
- "lastUpdated": "1565681352",
- "updateCount": 3,
- "authorCount": 2
- }
- },
- {
- "id": "fibonacciCountUntilNum",
- "title": "fibonacciCountUntilNum",
- "type": "snippet",
- "attributes": {
- "fileName": "fibonacciCountUntilNum.md",
- "text": "Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive).\n\nUse a mathematical formula to calculate the number of fibonacci numbers until `num`.\n\n",
- "codeBlocks": {
- "es6": "const fibonacciCountUntilNum = num =>\n Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));",
- "es5": "var fibonacciCountUntilNum = function fibonacciCountUntilNum(num) {\n return Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n};",
- "example": "fibonacciCountUntilNum(10); // 7"
- },
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "35488eb0f56b59035b56cc67fa0a5e1a970162ede4aafd97ebb2b4009c321c01",
- "firstSeen": "1515162834",
- "lastUpdated": "1565681352",
- "updateCount": 3,
- "authorCount": 2
- }
- },
- {
- "id": "fibonacciUntilNum",
- "title": "fibonacciUntilNum",
- "type": "snippet",
- "attributes": {
- "fileName": "fibonacciUntilNum.md",
- "text": "Generates an array, containing the Fibonacci sequence, up until the nth term.\n\nCreate an empty array of the specific length, initializing the first two values (`0` and `1`).\nUse `Array.prototype.reduce()` to add values into the array, using the sum of the last two values, except for the first two.\nUses a mathematical formula to calculate the length of the array required.\n\n",
- "codeBlocks": {
- "es6": "const fibonacciUntilNum = num => {\n let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n return Array.from({ length: n }).reduce(\n (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),\n []\n );\n};",
- "es5": "var fibonacciUntilNum = function fibonacciUntilNum(num) {\n var n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));\n return Array.from({\n length: n\n }).reduce(function (acc, val, i) {\n return acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i);\n }, []);\n};",
- "example": "fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]"
- },
- "tags": [
- "math",
- "intermediate"
- ]
- },
- "meta": {
- "hash": "6ff845c13444a06569be548ce9e69900b7001516c44c315795f34b31e9baa833",
- "firstSeen": "1515162834",
- "lastUpdated": "1565681352",
- "updateCount": 4,
- "authorCount": 3
- }
- },
- {
- "id": "heronArea",
- "title": "heronArea",
- "type": "snippet",
- "attributes": {
- "fileName": "heronArea.md",
- "text": "Returns the area of a triangle using only the 3 side lengths, Heron's formula. Assumes that the sides define a valid triangle. Does NOT assume it is a right triangle.\n\nMore information on what Heron's formula is and why it works available here: https://en.wikipedia.org/wiki/Heron%27s_formula.\n\nUses `Math.sqrt()` to find the square root of a value.\n\n",
- "codeBlocks": {
- "es6": "const heronArea = (side_a, side_b, side_c) => {\n const p = (side_a + side_b + side_c) / 2\n return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))\n };",
- "es5": "var heronArea = function heronArea(side_a, side_b, side_c) {\n var p = (side_a + side_b + side_c) / 2;\n return Math.sqrt(p * (p - side_a) * (p - side_b) * (p - side_c));\n};",
- "example": "heronArea(3, 4, 5); // 6"
- },
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "d0be594ab377cbeb2910308610af5890b3468c06e7567cd0995a84d11aaccf47",
- "firstSeen": "1538938431",
- "lastUpdated": "1565681352",
- "updateCount": 3,
- "authorCount": 3
- }
- },
- {
- "id": "howManyTimes",
- "title": "howManyTimes",
- "type": "snippet",
- "attributes": {
- "fileName": "howManyTimes.md",
- "text": "Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer.\nWorks for both negative and positive integers.\n\nIf `divisor` is `-1` or `1` return `Infinity`.\nIf `divisor` is `-0` or `0` return `0`.\nOtherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer.\nReturn the number of times the loop was executed, `i`.\n\n",
- "codeBlocks": {
- "es6": "const howManyTimes = (num, divisor) => {\n if (divisor === 1 || divisor === -1) return Infinity;\n if (divisor === 0) return 0;\n let i = 0;\n while (Number.isInteger(num / divisor)) {\n i++;\n num = num / divisor;\n }\n return i;\n};",
- "es5": "var howManyTimes = function howManyTimes(num, divisor) {\n if (divisor === 1 || divisor === -1) return Infinity;\n if (divisor === 0) return 0;\n var i = 0;\n\n while (Number.isInteger(num / divisor)) {\n i++;\n num = num / divisor;\n }\n\n return i;\n};",
- "example": "howManyTimes(100, 2); // 2\nhowManyTimes(100, 2.5); // 2\nhowManyTimes(100, 0); // 0\nhowManyTimes(100, -1); // Infinity"
- },
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "52ffa251dfc4e2bec7160a9066ef24a8c3047706e1ad2837f9d987cdf4d5f73e",
- "firstSeen": "1515162834",
- "lastUpdated": "1565681352",
- "updateCount": 3,
- "authorCount": 2
- }
- },
- {
- "id": "httpDelete",
- "title": "httpDelete",
- "type": "snippet",
- "attributes": {
- "fileName": "httpDelete.md",
- "text": "Makes a `DELETE` request to the passed URL.\n\nUse `XMLHttpRequest` web api to make a `delete` request to the given `url`.\nHandle the `onload` event, by running the provided `callback` function.\nHandle the `onerror` event, by running the provided `err` function.\nOmit the third argument, `err` to log the request to the console's error stream by default.\n\n",
- "codeBlocks": {
- "es6": "const httpDelete = (url, callback, err = console.error) => {\n const request = new XMLHttpRequest();\n request.open('DELETE', url, true);\n request.onload = () => callback(request);\n request.onerror = () => err(request);\n request.send();\n};",
- "es5": "var httpDelete = function httpDelete(url, callback) {\n var err = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : console.error;\n var request = new XMLHttpRequest();\n request.open('DELETE', url, true);\n\n request.onload = function () {\n return callback(request);\n };\n\n request.onerror = function () {\n return err(request);\n };\n\n request.send();\n};",
- "example": "httpDelete('https://website.com/users/123', request => {\n console.log(request.responseText);\n}); // 'Deletes a user from the database'"
- },
- "tags": [
- "browser",
- "intermediate"
- ]
- },
- "meta": {
- "hash": "4fccb2abe966313a742d13965ee46cfd1094763a2697591eddb19c1c5af1db7e",
- "firstSeen": "1515608606",
- "lastUpdated": "1565681352",
- "updateCount": 4,
- "authorCount": 3
- }
- },
- {
- "id": "httpPut",
- "title": "httpPut",
- "type": "snippet",
- "attributes": {
- "fileName": "httpPut.md",
- "text": "Makes a `PUT` request to the passed URL.\n\nUse `XMLHttpRequest` web api to make a `put` request to the given `url`.\nSet the value of an `HTTP` request header with `setRequestHeader` method.\nHandle the `onload` event, by running the provided `callback` function.\nHandle the `onerror` event, by running the provided `err` function.\nOmit the last argument, `err` to log the request to the console's error stream by default.\n\n",
- "codeBlocks": {
- "es6": "const httpPut = (url, data, callback, err = console.error) => {\n const request = new XMLHttpRequest();\n request.open(\"PUT\", url, true);\n request.setRequestHeader('Content-type','application/json; charset=utf-8');\n request.onload = () => callback(request);\n request.onerror = () => err(request);\n request.send(data);\n};",
- "es5": "var httpPut = function httpPut(url, data, callback) {\n var err = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : console.error;\n var request = new XMLHttpRequest();\n request.open(\"PUT\", url, true);\n request.setRequestHeader('Content-type', 'application/json; charset=utf-8');\n\n request.onload = function () {\n return callback(request);\n };\n\n request.onerror = function () {\n return err(request);\n };\n\n request.send(data);\n};",
- "example": "const password = \"fooBaz\";\nconst data = JSON.stringify(password);\nhttpPut('https://website.com/users/123', data, request => {\n console.log(request.responseText);\n}); // 'Updates a user's password in database'"
- },
- "tags": [
- "browser",
- "intermediate"
- ]
- },
- "meta": {
- "hash": "7eb4b1ffc1cbe28c10190bb82b7731ade2d79e78a5569bdee62af33a1020f2f5",
- "firstSeen": "1515608606",
- "lastUpdated": "1565681352",
- "updateCount": 4,
- "authorCount": 3
- }
- },
- {
- "id": "isArmstrongNumber",
- "title": "isArmstrongNumber",
- "type": "snippet",
- "attributes": {
- "fileName": "isArmstrongNumber.md",
- "text": "Checks if the given number is an Armstrong number or not.\n\nConvert the given number into an array of digits. Use the exponent operator (`**`) to get the appropriate power for each digit and sum them up. If the sum is equal to the number itself, return `true` otherwise `false`.\n\n",
- "codeBlocks": {
- "es6": "const isArmstrongNumber = digits =>\n (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(\n (digits + '').split('')\n );",
- "es5": "var isArmstrongNumber = function isArmstrongNumber(digits) {\n return function (arr) {\n return arr.reduce(function (a, d) {\n return a + Math.pow(parseInt(d), arr.length);\n }, 0) == digits;\n }((digits + '').split(''));\n};",
- "example": "isArmstrongNumber(1634); // true\nisArmstrongNumber(56); // false"
- },
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "71ebcdb61794d8222fcf447509d206ffb10dc8068072a88c6b587e21e76fc7f2",
- "firstSeen": "1515162834",
- "lastUpdated": "1565681352",
- "updateCount": 3,
- "authorCount": 2
- }
- },
- {
- "id": "isSimilar",
- "title": "isSimilar",
- "type": "snippet",
- "attributes": {
- "fileName": "isSimilar.md",
- "text": "Determines if the `pattern` matches with `str`.\n\nUse `String.toLowerCase()` to convert both strings to lowercase, then loop through `str` and determine if it contains all characters of `pattern` and in the correct order.\nAdapted from [here](https://github.com/forrestthewoods/lib_fts/blob/80f3f8c52db53428247e741b9efe2cde9667050c/code/fts_fuzzy_match.js#L18).\n\n",
- "codeBlocks": {
- "es6": "const isSimilar = (pattern, str) =>\n [...str].reduce(\n (matchIndex, char) =>\n char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase()\n ? matchIndex + 1\n : matchIndex,\n 0\n ) === pattern.length;",
- "es5": "function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance\"); }\n\nfunction _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === \"[object Arguments]\") return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }\n\nvar isSimilar = function isSimilar(pattern, str) {\n return _toConsumableArray(str).reduce(function (matchIndex, _char) {\n return _char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase() ? matchIndex + 1 : matchIndex;\n }, 0) === pattern.length;\n};",
- "example": "isSimilar('rt','Rohit'); // true\nisSimilar('tr','Rohit'); // false"
- },
- "tags": [
- "string",
- "intermediate"
- ]
- },
- "meta": {
- "hash": "250615cfc281e99014b97d054c722d3ba6aa4190ccf66dd719e530ec80aec3bd",
- "firstSeen": "1519637807",
- "lastUpdated": "1565681352",
- "updateCount": 7,
- "authorCount": 5
- }
- },
- {
- "id": "JSONToDate",
- "title": "JSONToDate",
- "type": "snippet",
- "attributes": {
- "fileName": "JSONToDate.md",
- "text": "Converts a JSON object to a date.\n\nUse `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).\n\n",
- "codeBlocks": {
- "es6": "const JSONToDate = arr => {\n const dt = new Date(parseInt(arr.toString().substr(6)));\n return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;\n};",
- "es5": "var JSONToDate = function JSONToDate(arr) {\n var dt = new Date(parseInt(arr.toString().substr(6)));\n return \"\".concat(dt.getDate(), \"/\").concat(dt.getMonth() + 1, \"/\").concat(dt.getFullYear());\n};",
- "example": "JSONToDate(/Date(1489525200000)/); // \"14/3/2017\""
- },
- "tags": [
- "object",
- "date",
- "beginner"
- ]
- },
- "meta": {
- "hash": "33e1e304fead4088971a60d4da974d0e9380370560f383ddb1ddc14e628df18b",
- "firstSeen": "1515162834",
- "lastUpdated": "1565681352",
- "updateCount": 3,
- "authorCount": 2
- }
- },
- {
- "id": "kmphToMph",
- "title": "kmphToMph",
- "type": "snippet",
- "attributes": {
- "fileName": "kmphToMph.md",
- "text": "Convert kilometers/hour to miles/hour.\n\nMultiply the constant of proportionality with the argument.\n\n",
- "codeBlocks": {
- "es6": "const kmphToMph = (kmph) => 0.621371192 * kmph;",
- "es5": "var kmphToMph = function kmphToMph(kmph) {\n return 0.621371192 * kmph;\n};",
- "example": "kmphToMph(10); // 16.09344000614692\nkmphToMph(345.4); // 138.24264965280207"
- },
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "f885a599e1185f8480445e1eb0c4a5cb8bf33948d7893f013dd4e8085478fe7a",
- "firstSeen": "1539710543",
- "lastUpdated": "1565681352",
- "updateCount": 3,
- "authorCount": 2
- }
- },
- {
- "id": "levenshteinDistance",
- "title": "levenshteinDistance",
- "type": "snippet",
- "attributes": {
- "fileName": "levenshteinDistance.md",
- "text": "Calculates the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between two strings.\n\nCalculates the number of changes (substitutions, deletions or additions) required to convert `string1` to `string2`. \nCan also be used to compare two strings as shown in the second example.\n\n",
- "codeBlocks": {
- "es6": "const levenshteinDistance = (string1, string2) => {\n if (string1.length === 0) return string2.length;\n if (string2.length === 0) return string1.length;\n let matrix = Array(string2.length + 1)\n .fill(0)\n .map((x, i) => [i]);\n matrix[0] = Array(string1.length + 1)\n .fill(0)\n .map((x, i) => i);\n for (let i = 1; i <= string2.length; i++) {\n for (let j = 1; j <= string1.length; j++) {\n if (string2[i - 1] === string1[j - 1]) {\n matrix[i][j] = matrix[i - 1][j - 1];\n } else {\n matrix[i][j] = Math.min(\n matrix[i - 1][j - 1] + 1,\n matrix[i][j - 1] + 1,\n matrix[i - 1][j] + 1\n );\n }\n }\n }\n return matrix[string2.length][string1.length];\n};",
- "es5": "var levenshteinDistance = function levenshteinDistance(string1, string2) {\n if (string1.length === 0) return string2.length;\n if (string2.length === 0) return string1.length;\n var matrix = Array(string2.length + 1).fill(0).map(function (x, i) {\n return [i];\n });\n matrix[0] = Array(string1.length + 1).fill(0).map(function (x, i) {\n return i;\n });\n\n for (var i = 1; i <= string2.length; i++) {\n for (var j = 1; j <= string1.length; j++) {\n if (string2[i - 1] === string1[j - 1]) {\n matrix[i][j] = matrix[i - 1][j - 1];\n } else {\n matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j] + 1);\n }\n }\n }\n\n return matrix[string2.length][string1.length];\n};",
- "example": "levenshteinDistance('30-seconds-of-code','30-seconds-of-python-code'); // 7\nconst compareStrings = (string1,string2) => (100 - levenshteinDistance(string1,string2) / Math.max(string1.length,string2.length));\ncompareStrings('30-seconds-of-code', '30-seconds-of-python-code'); // 99.72 (%)"
- },
- "tags": [
- "algorithm",
- "advanced"
- ]
- },
- "meta": {
- "hash": "9f71509c5937cb68b65ef31893b1ad723ce6690e8ecd161707cb222ab67a475b",
- "firstSeen": "1519637486",
- "lastUpdated": "1565681352",
- "updateCount": 7,
- "authorCount": 4
- }
- },
- {
- "id": "mphToKmph",
- "title": "mphToKmph",
- "type": "snippet",
- "attributes": {
- "fileName": "mphToKmph.md",
- "text": "Convert miles/hour to kilometers/hour.\n\nMultiply the constant of proportionality with the argument.\n\n",
- "codeBlocks": {
- "es6": "const mphToKmph = (mph) => 1.6093440006146922 * mph;",
- "es5": "var mphToKmph = function mphToKmph(mph) {\n return 1.6093440006146922 * mph;\n};",
- "example": "mphToKmph(10); // 16.09344000614692\nmphToKmph(85.9); // 138.24264965280207"
- },
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "d1ec7968c8f8c48642a3f91878db84330231bdf84bf74633dc0754456e951338",
- "firstSeen": "1539710543",
- "lastUpdated": "1565681352",
- "updateCount": 3,
- "authorCount": 2
- }
- },
- {
- "id": "objectToEntries",
- "title": "objectToEntries",
- "type": "snippet",
- "attributes": {
- "fileName": "objectToEntries.md",
- "text": "Creates an array of key-value pair arrays from an object.\n\nUse `Object.keys()` and `Array.prototype.map()` to iterate over the object's keys and produce an array with key-value pairs.\n\n",
- "codeBlocks": {
- "es6": "const objectToEntries = obj => Object.keys(obj).map(k => [k, obj[k]]);",
- "es5": "var objectToEntries = function objectToEntries(obj) {\n return Object.keys(obj).map(function (k) {\n return [k, obj[k]];\n });\n};",
- "example": "objectToEntries({ a: 1, b: 2 }); // [ ['a', 1], ['b', 2] ]"
- },
- "tags": [
- "object",
- "array",
- "beginner"
- ]
- },
- "meta": {
- "hash": "da5ab6a4f794f33d985d8a82794414b80913e63214a80d78c87bbda9638faa4f",
- "firstSeen": "1584968830",
- "lastUpdated": "1584968830",
- "updateCount": 2,
- "authorCount": 2
- }
- },
- {
- "id": "pipeLog",
- "title": "pipeLog",
- "type": "snippet",
- "attributes": {
- "fileName": "pipeLog.md",
- "text": "Logs a value and returns it.\n\nUse `console.log` to log the supplied value, combined with the `||` operator to return it.\n\n",
- "codeBlocks": {
- "es6": "const pipeLog = data => console.log(data) || data;",
- "es5": "var pipeLog = function pipeLog(data) {\n return console.log(data) || data;\n};",
- "example": "pipeLog(1); // logs `1` and returns `1`"
- },
- "tags": [
- "utility",
- "beginner"
- ]
- },
- "meta": {
- "hash": "dba6fa36424c23d601c4e463463a5f23d32b51d8b058a6c5020d3b4098a65e51",
- "firstSeen": "1537616292",
- "lastUpdated": "1565681352",
- "updateCount": 3,
- "authorCount": 2
- }
- },
- {
- "id": "quickSort",
- "title": "quickSort",
- "type": "snippet",
- "attributes": {
- "fileName": "quickSort.md",
- "text": "QuickSort an Array (ascending sort by default).\n\nUse recursion.\nUse `Array.prototype.filter` and spread operator (`...`) to create an array that all elements with values less than the pivot come before the pivot, and all elements with values greater than the pivot come after it.\nIf the parameter `desc` is truthy, return array sorts in descending order.\n\n",
- "codeBlocks": {
- "es6": "const quickSort = ([n, ...nums], desc) =>\n isNaN(n)\n ? []\n : [\n ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc),\n n,\n ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)\n ];",
- "es5": "function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance\"); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }\n\nfunction _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === \"[object Arguments]\") return Array.from(iter); }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nvar quickSort = function quickSort(_ref, desc) {\n var _ref2 = _toArray(_ref),\n n = _ref2[0],\n nums = _ref2.slice(1);\n\n return isNaN(n) ? [] : [].concat(_toConsumableArray(quickSort(nums.filter(function (v) {\n return desc ? v > n : v <= n;\n }), desc)), [n], _toConsumableArray(quickSort(nums.filter(function (v) {\n return !desc ? v > n : v <= n;\n }), desc)));\n};",
- "example": "quickSort([4, 1, 3, 2]); // [1,2,3,4]\nquickSort([4, 1, 3, 2], true); // [4,3,2,1]"
- },
- "tags": [
- "algorithm",
- "recursion",
- "beginner"
- ]
- },
- "meta": {
- "hash": "5c26069a02342eadd2c5ba2656a1b211da8f1a94da03c2cc31a5090be556d7b7",
- "firstSeen": "1515162834",
- "lastUpdated": "1565681352",
- "updateCount": 4,
- "authorCount": 3
- }
- },
- {
- "id": "removeVowels",
- "title": "removeVowels",
- "type": "snippet",
- "attributes": {
- "fileName": "removeVowels.md",
- "text": "Returns all the vowels in a `str` replaced by `repl`.\n\nUse `String.prototype.replace()` with a regexp to replace all vowels in `str`.\nOmot `repl` to use a default value of `''`.\n\n",
- "codeBlocks": {
- "es6": "const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);",
- "es5": "var removeVowels = function removeVowels(str) {\n var repl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n return str.replace(/[aeiou]/gi, repl);\n};",
- "example": "removeVowels(\"foobAr\"); // \"fbr\"\nremoveVowels(\"foobAr\",\"*\"); // \"f**b*r\""
- },
- "tags": [
- "string",
- "beginner"
- ]
- },
- "meta": {
- "hash": "5c6f8e292db8506568de362aa63890047f9d5a65d35143cfca1e27562642c414",
- "firstSeen": "1515500549",
- "lastUpdated": "1565681352",
- "updateCount": 5,
- "authorCount": 3
- }
- },
- {
- "id": "solveRPN",
- "title": "solveRPN",
- "type": "snippet",
- "attributes": {
- "fileName": "solveRPN.md",
- "text": "Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation).\nThrows appropriate errors if there are unrecognized symbols or the expression is wrong. The valid operators are :- `+`,`-`,`*`,`/`,`^`,`**` (`^`&`**` are the exponential symbols and are same). This snippet does not supports any unary operators.\n\nUse a dictionary, `OPERATORS` to specify each operator's matching mathematical operation.\nUse `String.prototype.replace()` with a regular expression to replace `^` with `**`, `String.prototype.split()` to tokenize the string and `Array.prototype.filter()` to remove empty tokens.\nUse `Array.prototype.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression.\nNumeric values are converted to floating point numbers and pushed to a `stack`, while operators are evaluated using the `OPERATORS` dictionary and pop elements from the `stack` to apply operations.\n\n",
- "codeBlocks": {
- "es6": "const solveRPN = rpn => {\n const OPERATORS = {\n '*': (a, b) => a * b,\n '+': (a, b) => a + b,\n '-': (a, b) => a - b,\n '/': (a, b) => a / b,\n '**': (a, b) => a ** b\n };\n const [stack, solve] = [\n [],\n rpn\n .replace(/\\^/g, '**')\n .split(/\\s+/g)\n .filter(el => !/\\s+/.test(el) && el !== '')\n ];\n solve.forEach(symbol => {\n if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {\n stack.push(symbol);\n } else if (Object.keys(OPERATORS).includes(symbol)) {\n const [a, b] = [stack.pop(), stack.pop()];\n stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));\n } else {\n throw `${symbol} is not a recognized symbol`;\n }\n });\n if (stack.length === 1) return stack.pop();\n else throw `${rpn} is not a proper RPN. Please check it and try again`;\n};",
- "es5": "var solveRPN = function solveRPN(rpn) {\n var OPERATORS = {\n '*': function _(a, b) {\n return a * b;\n },\n '+': function _(a, b) {\n return a + b;\n },\n '-': function _(a, b) {\n return a - b;\n },\n '/': function _(a, b) {\n return a / b;\n },\n '**': function _(a, b) {\n return Math.pow(a, b);\n }\n };\n var _ref = [[], rpn.replace(/\\^/g, '**').split(/\\s+/g).filter(function (el) {\n return !/\\s+/.test(el) && el !== '';\n })],\n stack = _ref[0],\n solve = _ref[1];\n solve.forEach(function (symbol) {\n if (!isNaN(parseFloat(symbol)) && isFinite(symbol)) {\n stack.push(symbol);\n } else if (Object.keys(OPERATORS).includes(symbol)) {\n var _ref2 = [stack.pop(), stack.pop()],\n a = _ref2[0],\n b = _ref2[1];\n stack.push(OPERATORS[symbol](parseFloat(b), parseFloat(a)));\n } else {\n throw \"\".concat(symbol, \" is not a recognized symbol\");\n }\n });\n if (stack.length === 1) return stack.pop();else throw \"\".concat(rpn, \" is not a proper RPN. Please check it and try again\");\n};",
- "example": "solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5\nsolveRPN('2 3 ^'); // 8"
- },
- "tags": [
- "algorithm",
- "advanced"
- ]
- },
- "meta": {
- "hash": "0c37cf46586652fd20dfa9ca682d3635f01fe61c46864f9773f6b258e8f3b6f6",
- "firstSeen": "1515162834",
- "lastUpdated": "1565681352",
- "updateCount": 4,
- "authorCount": 3
- }
- },
- {
- "id": "speechSynthesis",
- "title": "speechSynthesis",
- "type": "snippet",
- "attributes": {
- "fileName": "speechSynthesis.md",
- "text": "Performs speech synthesis (experimental).\n\nUse `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech.\nUse `window.speechSynthesis.speak()` to play the message.\n\nLearn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance).\n\n",
- "codeBlocks": {
- "es6": "const speechSynthesis = message => {\n const msg = new SpeechSynthesisUtterance(message);\n msg.voice = window.speechSynthesis.getVoices()[0];\n window.speechSynthesis.speak(msg);\n};",
- "es5": "var speechSynthesis = function speechSynthesis(message) {\n var msg = new SpeechSynthesisUtterance(message);\n msg.voice = window.speechSynthesis.getVoices()[0];\n window.speechSynthesis.speak(msg);\n};",
- "example": "speechSynthesis('Hello, World'); // // plays the message"
- },
- "tags": [
- "browser",
- "intermediate"
- ]
- },
- "meta": {
- "hash": "9859dbef05dc0398e825150b50fccfea370583cf6b807c00c9e83b769d2b51c0",
- "firstSeen": "1515162834",
- "lastUpdated": "1565681352",
- "updateCount": 3,
- "authorCount": 2
- }
- },
- {
- "id": "squareSum",
- "title": "squareSum",
- "type": "snippet",
- "attributes": {
- "fileName": "squareSum.md",
- "text": "Squares each number in an array and then sums the results together.\n\nUse `Array.prototype.reduce()` in combination with `Math.pow()` to iterate over numbers and sum their squares into an accumulator.\n\n",
- "codeBlocks": {
- "es6": "const squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0);",
- "es5": "var squareSum = function squareSum() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return args.reduce(function (squareSum, number) {\n return squareSum + Math.pow(number, 2);\n }, 0);\n};",
- "example": "squareSum(1, 2, 2); // 9"
- },
- "tags": [
- "math",
- "beginner"
- ]
- },
- "meta": {
- "hash": "19837ac6714833e9c5fe698811e171cc2598f7b9405a4847b33b8d3b35debf8a",
- "firstSeen": "1539593592",
- "lastUpdated": "1565681352",
- "updateCount": 7,
- "authorCount": 3
- }
- }
- ],
- "meta": {
- "specification": "http://jsonapi.org/format/",
- "type": "snippetArray",
- "scope": "./snippets_archive",
- "language": {
- "short": "js",
- "long": "JavaScript"
- }
- }
-}
\ No newline at end of file
diff --git a/snippet_data/glossaryTerms.json b/snippet_data/glossaryTerms.json
deleted file mode 100644
index e2a3f317c..000000000
--- a/snippet_data/glossaryTerms.json
+++ /dev/null
@@ -1,1395 +0,0 @@
-{
- "data": [
- {
- "id": "AJAX",
- "type": "glossaryTerm",
- "title": "AJAX",
- "attributes": {
- "text": "Asynchronous JavaScript and XML (known as AJAX) is a term that describes a new approach to using multiple technologies together in order to enable web applications to make quick updates to the user interface without reloading the entire browser page.\n",
- "tags": [
- "AJAX"
- ]
- },
- "meta": {
- "hash": "69b3cf5153fa3348e5863392fb2d0ee3c0c7caaf4f1006bbdb65fb8ea3b365af"
- }
- },
- {
- "id": "API",
- "type": "glossaryTerm",
- "title": "API",
- "attributes": {
- "text": "API stands for Application Programming Interface and is a set of features and rules provided by a provided by a software to enable third-party software to interact with it.\nThe code features of a web API usually include methods, properties, events or URLs.\n",
- "tags": [
- "API"
- ]
- },
- "meta": {
- "hash": "4a38caef0e8879fbe91f96c5d1f61c1628276502f4bb02da38ec79c75bd0e27a"
- }
- },
- {
- "id": "Argument",
- "type": "glossaryTerm",
- "title": "Argument",
- "attributes": {
- "text": "An argument is a value passed as an input to a function and can be either a primitive or an object.\nIn JavaScript, functions can also be passed as arguments to other functions.\n",
- "tags": [
- "Argument"
- ]
- },
- "meta": {
- "hash": "bb18f4bf7ba352a918752f5fae6c1838acba0c1a355d270e649b008e3e5be183"
- }
- },
- {
- "id": "Array",
- "type": "glossaryTerm",
- "title": "Array",
- "attributes": {
- "text": "Arrays are used to store multiple values in a single variable.\nArrays are ordered and each item in an array has a numeric index associated with it.\nJavaScript arrays are zero-indexed, meaning the first element's index is 0.\n",
- "tags": [
- "Array"
- ]
- },
- "meta": {
- "hash": "5a8b7e5f9ac56f1008cc87c308371c282d3122746f8908ff80dbc1cdae613ef3"
- }
- },
- {
- "id": "Asynchronous-programming",
- "type": "glossaryTerm",
- "title": "Asynchronous programming",
- "attributes": {
- "text": "Asynchronous programming is a way to allow multiple events to trigger code without waiting for each other.\nThe main benefits of asynchronous programming are improved application performance and responsiveness.\n",
- "tags": [
- "Asynchronous programming"
- ]
- },
- "meta": {
- "hash": "1a44acdc588be78c7c331704b9b4ab95b461eba5b55d70ebaae484b4cf625d6f"
- }
- },
- {
- "id": "Automatic-semicolon-insertion",
- "type": "glossaryTerm",
- "title": "Automatic semicolon insertion",
- "attributes": {
- "text": "Automatic semicolon insertion (ASI) is a JavaScript feature that allows developers to omit semicolons in their code.\n",
- "tags": [
- "Automatic semicolon insertion"
- ]
- },
- "meta": {
- "hash": "510b08853e3816e62aba98e3f824bec05b124e6d1b5919bfc09319b7e9486570"
- }
- },
- {
- "id": "Boolean",
- "type": "glossaryTerm",
- "title": "Boolean",
- "attributes": {
- "text": "Booleans are one of the primitive data types in JavaScript. \nThey represent logical data values and can only be `true` or `false`.\n",
- "tags": [
- "Boolean"
- ]
- },
- "meta": {
- "hash": "3f01c94cb306caf19a88b310c59fe7e488db661729afe6c100fba3c38be6e8a7"
- }
- },
- {
- "id": "Callback",
- "type": "glossaryTerm",
- "title": "Callback",
- "attributes": {
- "text": "A callback function, also known as a high-order function, is a function that is passed into another function as an argument, which is then executed inside the outer function.\nCallbacks can be synchronous or asynchronous.\n",
- "tags": [
- "Callback"
- ]
- },
- "meta": {
- "hash": "62b781aea272e769d6c92bd8daf99d99141af52462218727576ff207d341d65f"
- }
- },
- {
- "id": "Character-encoding",
- "type": "glossaryTerm",
- "title": "Character encoding",
- "attributes": {
- "text": "A character encoding defines a mapping between bytes and text, specifying how the sequenece of bytes should be interpreted.\nTwo commonly used character encodings are ASCII and UTF-8.\n",
- "tags": [
- "Character encoding"
- ]
- },
- "meta": {
- "hash": "9c638e81443d53eb1c59a3145716414105aed86ae4046772c63ff81bd4f605a1"
- }
- },
- {
- "id": "Class",
- "type": "glossaryTerm",
- "title": "Class",
- "attributes": {
- "text": "In object-oriented programming, a class is a template definition of an object's properties and methods.\n",
- "tags": [
- "Class"
- ]
- },
- "meta": {
- "hash": "e0c3dd77f0e3d05ed361dc491ab5fc81cb7d1be88e31e787e4bc45bd32171d2c"
- }
- },
- {
- "id": "Closure",
- "type": "glossaryTerm",
- "title": "Closure",
- "attributes": {
- "text": "A closure is the combination of a function and the lexical environment within which that function was declared.\nThe closure allows a function to access the contents of that environment.\n",
- "tags": [
- "Closure"
- ]
- },
- "meta": {
- "hash": "9c01b59507a6c71428df711d9089f92d8cb0b030356b061de8a4a6192bf39c93"
- }
- },
- {
- "id": "CoffeeScript",
- "type": "glossaryTerm",
- "title": "CoffeeScript",
- "attributes": {
- "text": "CoffeeScript is a programming language inspired by Ruby, Python and Haskell that transpiles to JavaScript.\n",
- "tags": [
- "CoffeeScript"
- ]
- },
- "meta": {
- "hash": "f1d55fd4b7da687507a0560f8878828a52a3b442d4462a344cea3324392ff66b"
- }
- },
- {
- "id": "Constant",
- "type": "glossaryTerm",
- "title": "Constant",
- "attributes": {
- "text": "A constant is a value, associated with an identifier.\nThe value of a constant can be accessed using the identifier and cannot be altered during execution.\n",
- "tags": [
- "Constant"
- ]
- },
- "meta": {
- "hash": "7c461f2980b6f1794518fd6b4b68166167fe912f8406144607c8da04d21908d7"
- }
- },
- {
- "id": "Constructor",
- "type": "glossaryTerm",
- "title": "Constructor",
- "attributes": {
- "text": "In class-based object-oriented programming, a constructor is a special type of function called to instantiate an object.\nConstructors often accept arguments that are commonly used to set member properties.\n",
- "tags": [
- "Constructor"
- ]
- },
- "meta": {
- "hash": "878d6b1ad8b17eebb1ac24969c4a4c269a65822a21c609221c3d96c7b989b108"
- }
- },
- {
- "id": "Continuous-Deployment",
- "type": "glossaryTerm",
- "title": "Continuous Deployment",
- "attributes": {
- "text": "Continuous Deployment follows the testing that happens during Continuous Integration and pushes changes to a staging or production system. \nContinuous Deployment ensures that a version of the codebase is accessible at all times.",
- "tags": [
- "Continuous Deployment"
- ]
- },
- "meta": {
- "hash": "2389500f32d8eead9e56735e78d7cc84a735b79f21ce87f902771e95290618f7"
- }
- },
- {
- "id": "Continuous-Integration",
- "type": "glossaryTerm",
- "title": "Continuous Integration",
- "attributes": {
- "text": "Continuous Integration (CI) is the practice of testing each change done to a codebase automatically and as early as possible.\nTwo popular CI systems that integrate with GitHub are Travis CI and Circle CI.",
- "tags": [
- "Continuous Integration"
- ]
- },
- "meta": {
- "hash": "5e494f687daab24e15c3853d0fccb90da6054f515f7cccd26801c6e0f38aaddc"
- }
- },
- {
- "id": "CORS",
- "type": "glossaryTerm",
- "title": "CORS",
- "attributes": {
- "text": "Cross-Origin Resource Sharing (known as CORS) is a mechanism that uses extra HTTP headers to tell a browser to let a web application running at one domain have permission to access resources from a server at a different domain.\n",
- "tags": [
- "CORS"
- ]
- },
- "meta": {
- "hash": "75d004b6c01c85c4ca20a4ffac0d859ba438f19319513e9f664ce3ce53abe699"
- }
- },
- {
- "id": "Cross-site-scripting-xss",
- "type": "glossaryTerm",
- "title": "Cross-site scripting (XSS)",
- "attributes": {
- "text": "XSS refers to client-side code injection where the attacker injects malicious scripts into a legitimate website or web application. \nThis is often achieved when the application does not validate user input and freely injects dynamic HTML content.\n",
- "tags": [
- "Cross-site scripting (XSS)"
- ]
- },
- "meta": {
- "hash": "ad0bd1bd6faba643e1ed7e5b1937a75209dffe5b995a4c19d57367c4311f836a"
- }
- },
- {
- "id": "CSS",
- "type": "glossaryTerm",
- "title": "CSS",
- "attributes": {
- "text": "CSS stands for Cascading Style Sheets and is a language used to style web pages.\nCSS documents are plaintext documents structured with rules, which consist of element selectors and property-value pairs that apply the styles to the specified selectors.\n",
- "tags": [
- "CSS"
- ]
- },
- "meta": {
- "hash": "fdbdbb8739e718f6be81222bda6e69e9f64f31ac786daa7d0a3118a145aee7f2"
- }
- },
- {
- "id": "CSV",
- "type": "glossaryTerm",
- "title": "CSV",
- "attributes": {
- "text": "CSV stands for Comma-Separated Values and is a storage format for tabular data.\nCSV documents are plaintext documents where each line represents a table row, with table columns separated by commas or some other delimiter (e.g. semicolons).\nThe first line of a CSV document sometimes consists of the table column headings for the data to follow.\n",
- "tags": [
- "CSV"
- ]
- },
- "meta": {
- "hash": "feee663243f2a5a800908ae230338d6b3c23f8b35b1c041be4e71c65123244bd"
- }
- },
- {
- "id": "Currying",
- "type": "glossaryTerm",
- "title": "Currying",
- "attributes": {
- "text": "Currying is a way of constructing functions that allows partial application of a function's arguments.\nPractically, this means that a function is broken down into a series of functions, each one accepting part of the arguments.\n",
- "tags": [
- "Currying"
- ]
- },
- "meta": {
- "hash": "964b862cd385b8c17273b7dc3a4621050cceb412a4e7840c3e279c55b983734b"
- }
- },
- {
- "id": "Deserialization",
- "type": "glossaryTerm",
- "title": "Deserialization",
- "attributes": {
- "text": "Deserialization is the process of converting a format that has been transferred over a network and/or used for storage to an object or data structure.\nA common type of deserialization in JavaScript is the conversion of JSON string into an object.\n",
- "tags": [
- "Deserialization"
- ]
- },
- "meta": {
- "hash": "9d60a691f67322c528e67a5d25fa97210117e7189e2a295bb400a91c1c5f7976"
- }
- },
- {
- "id": "DNS",
- "type": "glossaryTerm",
- "title": "DNS",
- "attributes": {
- "text": "A DNS (Domain Name System) translates domain names to the IP addresses needed to find a particular computer service on a network.\n",
- "tags": [
- "DNS"
- ]
- },
- "meta": {
- "hash": "8d465038cf1b0d10b1e13e87f1c62ca2b641f83dfcf52d6e15fc65c23017dc9e"
- }
- },
- {
- "id": "DOM",
- "type": "glossaryTerm",
- "title": "DOM",
- "attributes": {
- "text": "The DOM (Document Object Model) is a cross-platform API that treats HTML and XML documents as a tree structure consisting of nodes. \nThese nodes (such as elements and text nodes) are objects that can be programmatically manipulated and any visible changes made to them are reflected live in the document. \nIn a browser, this API is available to JavaScript where DOM nodes can be manipulated to change their styles, contents, placement in the document, or interacted with through event listeners.\n",
- "tags": [
- "DOM"
- ]
- },
- "meta": {
- "hash": "3fd8b63824d879f4b990a9fb67a60d733becda3ee74c2819f46515e563d19299"
- }
- },
- {
- "id": "Domain-name-registrar",
- "type": "glossaryTerm",
- "title": "Domain name registrar",
- "attributes": {
- "text": "A domain name registrar is a company that manages the reservation of internet domain names.\nA domain name registrar must be approved by a general top-level domain (gTLD) registry or a country code top-level domain (ccTLD) registry.\n",
- "tags": [
- "Domain name registrar"
- ]
- },
- "meta": {
- "hash": "ce222cb66f1299ffa59c08699cff464b5fb0daa8db3002007e8b8697f5ca5057"
- }
- },
- {
- "id": "Domain-name",
- "type": "glossaryTerm",
- "title": "Domain name",
- "attributes": {
- "text": "A domain name is a website's address on the Internet, used primarily in URLs to identify the server for each webpage.\nA domain name consists of a hierarchical sequence of names, separated by dots and ending with an extension.\n",
- "tags": [
- "Domain name"
- ]
- },
- "meta": {
- "hash": "0b478a7a88b2b463db686720064db6265b8b3161566815889ec6b00eb6e3ed20"
- }
- },
- {
- "id": "Element",
- "type": "glossaryTerm",
- "title": "Element",
- "attributes": {
- "text": "A JavaScript representation of a DOM element commonly returned by `document.querySelector()` and `document.createElement()`. \nThey are used when creating content with JavaScript for display in the DOM that needs to be programatically generated.\n",
- "tags": [
- "Element"
- ]
- },
- "meta": {
- "hash": "9ce0565b0108631bea1187d52c5423320eb4833e1de33b223083be9b877eede8"
- }
- },
- {
- "id": "ES6",
- "type": "glossaryTerm",
- "title": "ES6",
- "attributes": {
- "text": "ES6 stands for ECMAScript 6 (also known as ECMAScript 2015), a version of the ECMAScript specification that standardizes JavaScript.\nES6 adds a wide variety of new features to the specification, such as classes, promises, generators and arrow functions.\n",
- "tags": [
- "ES6"
- ]
- },
- "meta": {
- "hash": "0e3ebc232de61abfd21f7017ed3be1bc877437f26ae4a5df2284c9d1c0e6acf9"
- }
- },
- {
- "id": "Event-driven-programming",
- "type": "glossaryTerm",
- "title": "Event-driven programming",
- "attributes": {
- "text": "Event-driven programming is a programming paradigm in which the flow of the program is determined by events (e.g. user actions, thread messages, sensor outputs).\nIn event-driven applications, there is usually a main loop that listens for events and trigger callback functions accordingly when one of these events is detected.\n",
- "tags": [
- "Event-driven programming"
- ]
- },
- "meta": {
- "hash": "9c65cdbdb985a10049eb1de1402c316d257c5b667f625f0fc04a87cd4fdd32ac"
- }
- },
- {
- "id": "Event-loop",
- "type": "glossaryTerm",
- "title": "Event loop",
- "attributes": {
- "text": "The event loop handles all asynchronous callbacks. \nCallbacks are queued in a loop, while other code runs, and will run one by one when the response for each one has been received.\nThe event loop allows JavaScript to perform non-blocking I/O operations, despite the fact that JavaScript is single-threaded.\n",
- "tags": [
- "Event loop"
- ]
- },
- "meta": {
- "hash": "e3f7c2a5f8b2dab4bb5bc1cf04658e8b506825c9624fa260d82f797fc02e7c78"
- }
- },
- {
- "id": "Express",
- "type": "glossaryTerm",
- "title": "Express",
- "attributes": {
- "text": "Express is a backend framework, that provides a layer of fundamental web application features for Node.js.\nSome of its key features are routing, middleware, template engines and error handling.\n",
- "tags": [
- "Express"
- ]
- },
- "meta": {
- "hash": "29cee59e219e12f9e91bb3e6b9e80b019fed963913cd070ac7e1f7cfab842ef1"
- }
- },
- {
- "id": "Factory-functions",
- "type": "glossaryTerm",
- "title": "Factory functions",
- "attributes": {
- "text": "In JavaScript, a factory function is any function, which is not a class or constructor, that returns a new object.\nFactory functions don't require the use of the `new` keyword.\n",
- "tags": [
- "Factory functions"
- ]
- },
- "meta": {
- "hash": "a0c1c7de7ccb443a0430390da1004789762a4f9e6979cb9071f950897fa8e9d4"
- }
- },
- {
- "id": "First-class-function",
- "type": "glossaryTerm",
- "title": "First-class function",
- "attributes": {
- "text": "A programming language is said to have first-class functions if it treats them as first-class citizens, meaning they can be passed as arguments, be returned as values from other functions, be assigned to variables and stored in data structures.",
- "tags": [
- "First-class function"
- ]
- },
- "meta": {
- "hash": "499e7946c147d07e0a7dfa72334f89a36964f328929ec3b173f830b0bdc9a4da"
- }
- },
- {
- "id": "Flexbox",
- "type": "glossaryTerm",
- "title": "Flexbox",
- "attributes": {
- "text": "Flexbox is a one-dimensional layout model used to style websites as a property that could advance space distribution between items and provide powerful alignment capabilities.\n",
- "tags": [
- "Flexbox"
- ]
- },
- "meta": {
- "hash": "be1cc6d8fee2ab876af349d5d99bb1fc1a4cb7884fecbb9191d3d9e60d90a703"
- }
- },
- {
- "id": "Function",
- "type": "glossaryTerm",
- "title": "Function",
- "attributes": {
- "text": "Functions are self-contained blocks of code with their own scope, that can be called by other code and are usually associated with a unique identifier.\nFunctions accept input in the form of arguments and can optionally return an output (if no `return` statement is present, the default value of `undefined` will be returned instead). \nJavaScript functions are also objects.\n",
- "tags": [
- "Function"
- ]
- },
- "meta": {
- "hash": "12712370bee0ffd535998408f9977b94ac762fa6ff6b12e9b86359e14150c7af"
- }
- },
- {
- "id": "Functional-programming",
- "type": "glossaryTerm",
- "title": "Functional programming",
- "attributes": {
- "text": "Functional programming is a paradigm in which programs are built in a declarative manner using pure functions that avoid shared state and mutable data. \nFunctions that always return the same value for the same input and don't produce side effects are the pillar of functional programming.\n",
- "tags": [
- "Functional programming"
- ]
- },
- "meta": {
- "hash": "d774609fa3ba6788d4bacd501f6e658a7afca91526e04dd5a619cf3d30badee4"
- }
- },
- {
- "id": "Functor",
- "type": "glossaryTerm",
- "title": "Functor",
- "attributes": {
- "text": "A Functor is a data type common in functional programming that implements a `map` method. \nThe `map` method takes a function and applies it to the data in the Functor, returning a new instance of the Functor with the result.\nJavaScript `Array`s are an example of the Functor data type.\n",
- "tags": [
- "Functor"
- ]
- },
- "meta": {
- "hash": "389aaf215eaa534d4625d1aa6aba1e047ca4e7ef1241b4129867fa4e13438cbc"
- }
- },
- {
- "id": "Garbage-collection",
- "type": "glossaryTerm",
- "title": "Garbage collection",
- "attributes": {
- "text": "Garbage collection is a form of automatic memory management.\nIt attempts to reclaim memory occupied by objects that are no longer used by the program.\n",
- "tags": [
- "Garbage collection"
- ]
- },
- "meta": {
- "hash": "3c3a3376420cf16156ce79e62ea70363fd37710ea62490264bd851fed227cb6c"
- }
- },
- {
- "id": "Git",
- "type": "glossaryTerm",
- "title": "Git",
- "attributes": {
- "text": "Git is an open-source version control system, used for source code management.\nGit allows users to copy (clone) and edit code on their local machines, before merging it into the main code base (master repository).\n",
- "tags": [
- "Git"
- ]
- },
- "meta": {
- "hash": "25d2b0e1f222f102acdcfdedabfeec8f04b40ff808b61ce047de16f184484fa2"
- }
- },
- {
- "id": "Higher-order-function",
- "type": "glossaryTerm",
- "title": "Higher-order function",
- "attributes": {
- "text": "Higher-order functions are functions that either take other functions as arguments, return a function as a result, or both.\n",
- "tags": [
- "Higher-order function"
- ]
- },
- "meta": {
- "hash": "f7948fa3ad3524b004127eaf27cd023ce12a87b1d465e3f6e37af034d1239002"
- }
- },
- {
- "id": "Hoisting",
- "type": "glossaryTerm",
- "title": "Hoisting",
- "attributes": {
- "text": "Hoisting is JavaScript's default behavior of adding declarations to memory during the compile phase.\nHoisting allows for JavaScript variables to be used before the line they were declared on.\n",
- "tags": [
- "Hoisting"
- ]
- },
- "meta": {
- "hash": "7f45960c62541e01c3f7c28e75eb6e131272f81ff25d354031b2f0be1fb16ca4"
- }
- },
- {
- "id": "HTML",
- "type": "glossaryTerm",
- "title": "HTML",
- "attributes": {
- "text": "HTML stands for HyperText Markup Language and is a language used to structure web pages.\nHTML documents are plaintext documents structured with elements, which are surrounded by `<>` tags and optionally extended with attributes.\n",
- "tags": [
- "HTML"
- ]
- },
- "meta": {
- "hash": "e5e1a1dffda6d69ca6247f3a5e78e629d95a4ad80ef2bd23605556068d86f419"
- }
- },
- {
- "id": "HTTP-and-HTTPS",
- "type": "glossaryTerm",
- "title": "HTTP and HTTPS",
- "attributes": {
- "text": "The HyperText Transfer Protocol (HTTP) is the underlying network protocol that enables transfer of hypermedia documents on the Web, usually between a client and a server.\nThe HyperText Transfer Protocol Secure (HTTPS) is an encrypted version of the HTTP protocol, that uses SSL to encrypt all data transferred between a client and a server.\n",
- "tags": [
- "HTTP and HTTPS"
- ]
- },
- "meta": {
- "hash": "2c681c09ff405bc1c980151e4f1a3cfd54b415305bb6f3bcaf2b0cbcf9d05332"
- }
- },
- {
- "id": "Integer",
- "type": "glossaryTerm",
- "title": "Integer",
- "attributes": {
- "text": "Integers are one of the primitive data types in Javascript.\nThey represent a numerical value that has no fractional component.\n",
- "tags": [
- "Integer"
- ]
- },
- "meta": {
- "hash": "ca87340c4addebe9e1a4249fce62c0ef3e9d37505b2a834b95368c2d7250d2a8"
- }
- },
- {
- "id": "Integration-testing",
- "type": "glossaryTerm",
- "title": "Integration testing",
- "attributes": {
- "text": "Integration testing is a type of software testing, used to test groups of units/components of a software.\nThe purpose of integration tests are to validate that the units/components interact with each other as expected.\n",
- "tags": [
- "Integration testing"
- ]
- },
- "meta": {
- "hash": "f0cc0f86211a8f1ae66ea9be353f3c9adc0e56dec19579709ff6da3ebf388ace"
- }
- },
- {
- "id": "IP",
- "type": "glossaryTerm",
- "title": "IP",
- "attributes": {
- "text": "An IP address is a number assigned to a device connected to a network that uses the Internet protocol.\nTwo IP versions are currently in use - IPv4, the older version of the communication protocol (e.g. 192.168.1.100) and IPv6, the newest version of the communication protocol which allows for many different IP addresses (e.g. 0:0:0:0:ffff:c0a8:164).\n",
- "tags": [
- "IP"
- ]
- },
- "meta": {
- "hash": "e2812fdbe97a001ef10d72b95ffd9e4b4bdbe67e37ff7d1914eaea8583ae286c"
- }
- },
- {
- "id": "jQuery",
- "type": "glossaryTerm",
- "title": "jQuery",
- "attributes": {
- "text": "jQuery is a frontend JavaScript library, that simplifies DOM manipulation, AJAX calls and Event handling.\njQuery uses its globally defined function, `$()`, to select and manipulate DOM elements.\n",
- "tags": [
- "jQuery"
- ]
- },
- "meta": {
- "hash": "3b9ca98ed6c2c184e2e7bd30615fe3752c20d7c016afbf6673b005ee76d7aec4"
- }
- },
- {
- "id": "JSON",
- "type": "glossaryTerm",
- "title": "JSON",
- "attributes": {
- "text": "JSON (JavaScript Object Notation) is a format for storing and exchanging data.\nIt closely resembles the JavaScript object syntax, however some data types, such as dates and functions, cannot be natively represented and need to be serialized first.\n",
- "tags": [
- "JSON"
- ]
- },
- "meta": {
- "hash": "3e028e49f3eceb813e54013fb9bf05ef253efa4fa3034353c220cf28899952be"
- }
- },
- {
- "id": "MDN",
- "type": "glossaryTerm",
- "title": "MDN",
- "attributes": {
- "text": "MDN Web Docs, formerly known as Mozilla Developer Network, is the official Mozilla website for development documentation of web standards and Mozilla projects.\n",
- "tags": [
- "MDN"
- ]
- },
- "meta": {
- "hash": "61ae68cf3a3b1bbf43ffce76bdaa244fa0f5bc5dbdadcd4a06d5260f8dd3247a"
- }
- },
- {
- "id": "Module",
- "type": "glossaryTerm",
- "title": "Module",
- "attributes": {
- "text": "Modules are independent, self-contained pieces of code that can be incorporated into other pieces of code.\nModules improve maintainability and reusability of the code.\n",
- "tags": [
- "Module"
- ]
- },
- "meta": {
- "hash": "4e458b6078a1a91ed7da324aa1ac20cdbf290768aa395d3ab530d95238b7a05e"
- }
- },
- {
- "id": "MongoDB",
- "type": "glossaryTerm",
- "title": "MongoDB",
- "attributes": {
- "text": "MongoDB is a NoSQL database model that stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time\n",
- "tags": [
- "MongoDB"
- ]
- },
- "meta": {
- "hash": "c7ca87020640f844151f9422b6c473afd99620b7483f90142040cc46ffb9a7a7"
- }
- },
- {
- "id": "Mutabe-value",
- "type": "glossaryTerm",
- "title": "Mutable value",
- "attributes": {
- "text": "Mutable value is a type of variable that can be changed once created.\nObjects are mutable as their state can be modified after they are created.\nPrimitive values are not mutable as we perform reassignment once we change them.\n",
- "tags": [
- "Mutable value"
- ]
- },
- "meta": {
- "hash": "64da7def1e95f7220ef3bbf14568350c8cbf6abe187a6f539a64f9fb2067aa5d"
- }
- },
- {
- "id": "MVC",
- "type": "glossaryTerm",
- "title": "MVC",
- "attributes": {
- "text": "MVC stands for Model-View-Controller and is a software design pattern, emphasizing separation of concerns (logic and display).\nThe Model part of the MVC pattern refers to the data and business logic, the View handles the layout and display, while the Controller routes commands to the model and view parts. \n",
- "tags": [
- "MVC"
- ]
- },
- "meta": {
- "hash": "9956f9ca2dab4c5d7370f3a6ed38abbf871b6f5c11ffef6449e3791aa5229420"
- }
- },
- {
- "id": "Node-js",
- "type": "glossaryTerm",
- "title": "Node.js",
- "attributes": {
- "text": "Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine.\nNode.js can execute JavaScript code outside of the browser and can be used to develop web backends or standalone applications.\n",
- "tags": [
- "Node.js"
- ]
- },
- "meta": {
- "hash": "e03cbfde15c9f4b7c74ee034ed37f3d78809bd1ec64e2fdb62d2bf9da4c3c3ab"
- }
- },
- {
- "id": "NoSQL",
- "type": "glossaryTerm",
- "title": "NoSQL",
- "attributes": {
- "text": "NoSQL databases provide a mechanism to create, update, retrieve and calculate data that is stored in models that are non-tabular.",
- "tags": [
- "NoSQL"
- ]
- },
- "meta": {
- "hash": "1f948ede88ba138f4ae41bcb694b2837e59e2427bfadf2a5b62773453db4664a"
- }
- },
- {
- "id": "Npm",
- "type": "glossaryTerm",
- "title": "Npm",
- "attributes": {
- "text": "Npm is a package manager for the JavaScript programming language and the default package manager for Node.js.\nIt consists of a command-line client and the npm registry, an online database of packages.\n",
- "tags": [
- "Npm"
- ]
- },
- "meta": {
- "hash": "49873aab20ab7019d8253e102d9623f086558d464241f821ed6d3de67aa0a15c"
- }
- },
- {
- "id": "Object-oriented-programming",
- "type": "glossaryTerm",
- "title": "Object-oriented programming",
- "attributes": {
- "text": "Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which may contain both data and procedures which can be use to operate on them.\nJavaScript supports Object-oriented programming both via prototypes and classes.\n",
- "tags": [
- "Object-oriented programming"
- ]
- },
- "meta": {
- "hash": "501ba8d90343d16c419320e6896196c38e7b9b14e893ef96617f8bb108931b19"
- }
- },
- {
- "id": "Object",
- "type": "glossaryTerm",
- "title": "Object",
- "attributes": {
- "text": "Objects are data structures that contain data and instructions for working with the data.\nObjects consist of key-value pairs, where the keys are alphanumeric identifiers and the values can either be primitives or objects.\nJavaScript functions are also objects.\n",
- "tags": [
- "Object"
- ]
- },
- "meta": {
- "hash": "18066e6dbd116c3c589457fb5cef16b9a5728a87a4a096d91aa436c8e3aafdf4"
- }
- },
- {
- "id": "Prepared-statements",
- "type": "glossaryTerm",
- "title": "Prepared statements",
- "attributes": {
- "text": "In databases management systems, prepared statements are templates that can be used to execute queries with the provided values substituting the template's parameters.\nPrepared statements offer many benefits, such as reusability, maintainability and higher security.\n",
- "tags": [
- "Prepared statements"
- ]
- },
- "meta": {
- "hash": "5720bf41b264de168f79f6a5a4bd2bfb3e34e0bf14668e41d3473047fe606309"
- }
- },
- {
- "id": "Promise",
- "type": "glossaryTerm",
- "title": "Promise",
- "attributes": {
- "text": "The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.\nA Promise can be in one of these states: pending(initial state, neither fulfilled nor rejected), fulfilled(operation completed successfully), rejected(operation failed).\n",
- "tags": [
- "Promise"
- ]
- },
- "meta": {
- "hash": "ae5316c9f0178c362ae59e5c48d8e2bfca4bb4651e25696c16e7550851220251"
- }
- },
- {
- "id": "Prototype-based-programming",
- "type": "glossaryTerm",
- "title": "Prototype-based programming",
- "attributes": {
- "text": "Prototype-based programming is a style of object-oriented programming, where inheritance is based on object delegation, reusing objects that serve as prototypes.\nPrototype-based programming allows the creation of objects before defining their classes.\n",
- "tags": [
- "Prototype-based programming"
- ]
- },
- "meta": {
- "hash": "6a8d442044c67422c03c6e2d996380632d589c932b7d8bda1481196de230e83f"
- }
- },
- {
- "id": "Pseudo-class",
- "type": "glossaryTerm",
- "title": "Pseudo-class",
- "attributes": {
- "text": "In CSS, a pseudo-class is used to define a special state of an element and can be used as a selector in combination with an id, element or class selector.\n",
- "tags": [
- "Pseudo-class"
- ]
- },
- "meta": {
- "hash": "eb4de09ddad1a858923ec46b6b7fb4fd2ec04631ce53054fe3320e25b70650f4"
- }
- },
- {
- "id": "Pseudo-element",
- "type": "glossaryTerm",
- "title": "Pseudo-element",
- "attributes": {
- "text": "In CSS, a pseudo-element is used to style specific parts of an element and can be used as a selector in combination with an id, element or class selector.\n",
- "tags": [
- "Pseudo-element"
- ]
- },
- "meta": {
- "hash": "101704381209b0f0949dfe98c63a412dfc22736fb9b68adba02aaac76f97f606"
- }
- },
- {
- "id": "PWA",
- "type": "glossaryTerm",
- "title": "PWA",
- "attributes": {
- "text": "Progressive Web App (known as PWA) is a term used to describe web applications that load like regular websites but can offer the user functionality such as working offline, push notifications, and device hardware access that were traditionally available only to native mobile applications.\n",
- "tags": [
- "PWA"
- ]
- },
- "meta": {
- "hash": "ccf2722f73b32d2693b0cb050ab611f86539ce1ec620af3b277e00042e7e4402"
- }
- },
- {
- "id": "React",
- "type": "glossaryTerm",
- "title": "React",
- "attributes": {
- "text": "React is a frontend framework, that allows developers to create dynamic, component-based user interfaces.\nReact separates view and state, utilizing a virtual DOM to update the user interface.\n",
- "tags": [
- "React"
- ]
- },
- "meta": {
- "hash": "4a988d97fc5256e61d4c50677b4a78ffb17a34538b34e4bbba96a8ef1638c117"
- }
- },
- {
- "id": "Recursion",
- "type": "glossaryTerm",
- "title": "Recursion",
- "attributes": {
- "text": "Recursion is the repeated application of a process. \nIn JavaScript, recursion involves functions that call themselves repeatedly until they reach a base condition. \nThe base condition breaks out of the recursion loop because otherwise the function would call itself indefinitely. \nRecursion is very useful when working with nested data, especially when the nesting depth is dynamically defined or unknown.\n",
- "tags": [
- "Recursion"
- ]
- },
- "meta": {
- "hash": "8ccde135a72db896bd889ea27843eb9368d2a0874726aa7a2af67b30c1c57185"
- }
- },
- {
- "id": "Regular-expressions",
- "type": "glossaryTerm",
- "title": "Regular expressions",
- "attributes": {
- "text": "Regular expressions (known as regex or regexp) are patterns used to match character combinations in strings.\nJavaScript provides a regular expression implementation through the `RegExp` object.\n",
- "tags": [
- "Regular expressions"
- ]
- },
- "meta": {
- "hash": "657233cddce674de187be8e93e1c8b6e38c405505b1266ca1f3fb35b965e1df2"
- }
- },
- {
- "id": "Repository",
- "type": "glossaryTerm",
- "title": "Repository",
- "attributes": {
- "text": "In a version control system, a repository (or repo for short) is a data structure that stores metadata for a set of files (i.e. a project).\n",
- "tags": [
- "Repository"
- ]
- },
- "meta": {
- "hash": "b70059738193173e8ef6003dbd1b751d1c77921ac1b09f372fb0140c9356aab1"
- }
- },
- {
- "id": "Responsive-web-design",
- "type": "glossaryTerm",
- "title": "Responsive web design",
- "attributes": {
- "text": "Responsive web design is a web development concept aiming to provide optimal behavior and performance of websites on all web-enabled devices.\nResponsive web design is usually coupled with a mobile-first approach.\n",
- "tags": [
- "Responsive web design"
- ]
- },
- "meta": {
- "hash": "489ab55187ce67a6138db4c0e2606dbe808624effb398ac3a18edde27c16a868"
- }
- },
- {
- "id": "Scope",
- "type": "glossaryTerm",
- "title": "Scope",
- "attributes": {
- "text": "Each function has its own scope, and any variable declared within that function is only accessible from that function and any nested functions.\n",
- "tags": [
- "Scope"
- ]
- },
- "meta": {
- "hash": "e44cc3eaa39955a9044b5970b515287a4df2cf07599c9e55ad1ae4defbcc2229"
- }
- },
- {
- "id": "Selector",
- "type": "glossaryTerm",
- "title": "Selector",
- "attributes": {
- "text": "A CSS selector is a pattern that is used to select and/or style one or more elements in a document, based on certain rules.\nThe order in which CSS selectors apply styles to elements is based on the rules of CSS specificity.\n",
- "tags": [
- "Selector"
- ]
- },
- "meta": {
- "hash": "f17eb23b5bda4e18a346a107b8dfcb8fe2ae1b0ce325657ed6b505f3c756be3b"
- }
- },
- {
- "id": "SEO",
- "type": "glossaryTerm",
- "title": "SEO",
- "attributes": {
- "text": "SEO stands for Search Engine Optimization and refers to the process of improving a website's search rankings and visibility.\n",
- "tags": [
- "SEO"
- ]
- },
- "meta": {
- "hash": "1927b7df02d9e99369401756b6af641c68aa79e71f0e42afe5ccf812dae41709"
- }
- },
- {
- "id": "Serialization",
- "type": "glossaryTerm",
- "title": "Serialization",
- "attributes": {
- "text": "Serialization is the process of converting an object or data structure into a format suitable for transfer over a network and/or storage.\nA common type of serialization in JavaScript is the conversion of an object into a JSON string.\n",
- "tags": [
- "Serialization"
- ]
- },
- "meta": {
- "hash": "a91560cd1d2f68017e8ce5566b2a01e73201eaad0e79568e3b83d028ec29a45f"
- }
- },
- {
- "id": "ShadowDOM",
- "type": "glossaryTerm",
- "title": "Shadow DOM",
- "attributes": {
- "text": "Shadow DOM allows you to attach hidden DOM trees to elements in the normal DOM tree, which are included in the document rendering, but excluded from the main document DOM tree. \nA shadow DOM tree will start with a shadow root, to which you can attach any elements you want, just like in a regular DOM.\nExamples of shadow DOM uses are the `