Merge branch 'master' into event-utils

This commit is contained in:
Angelos Chalaris
2018-01-05 18:10:22 +02:00
committed by GitHub
70 changed files with 741 additions and 1071 deletions

918
README.md

File diff suppressed because it is too large Load Diff

1
advanced.svg Normal file
View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="78" height="20"><linearGradient id="b" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient><clipPath id="a"><rect height="20" rx="3" fill="#fff" width="64"/></clipPath><g clip-path="url(#a)"><path fill="#555" d="M0 0h65v20H0z"/></g><g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="110"><text x="325" y="150" fill="#010101" fill-opacity=".3" transform="scale(.1)" textLength="530">advanced</text><text x="325" y="140" transform="scale(.1)" textLength="530">advanced</text></g> </svg>

After

Width:  |  Height:  |  Size: 695 B

110
dist/_30s.es5.js vendored
View File

@ -248,9 +248,9 @@ var difference = function difference(a, b) {
var differenceWith = function differenceWith(arr, val, comp) { var differenceWith = function differenceWith(arr, val, comp) {
return arr.filter(function (a) { return arr.filter(function (a) {
return !val.find(function (b) { return val.findIndex(function (b) {
return comp(a, b); return comp(a, b);
}); }) === -1;
}); });
}; };
@ -301,20 +301,43 @@ var elementIsVisibleInViewport = function elementIsVisibleInViewport(el) {
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
function _toArray$1(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
var elo = function elo(_ref) { var elo = function elo(_ref) {
var _ref2 = _slicedToArray(_ref, 2), var _ref2 = _toArray$1(_ref),
a = _ref2[0], ratings = _ref2.slice(0);
b = _ref2[1];
var kFactor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 32; var kFactor = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 32;
var selfRating = arguments[2];
var _ratings = _slicedToArray(ratings, 2),
a = _ratings[0],
b = _ratings[1];
var expectedScore = function expectedScore(self, opponent) { var expectedScore = function expectedScore(self, opponent) {
return 1 / (1 + Math.pow(10, (opponent - self) / 400)); return 1 / (1 + Math.pow(10, (opponent - self) / 400));
}; };
var newRating = function newRating(rating, i) { var newRating = function newRating(rating, i) {
return rating + kFactor * (i - expectedScore(i ? a : b, i ? b : a)); return (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a));
}; };
return [newRating(a, 1), newRating(b, 0)]; if (ratings.length === 2) {
return [newRating(a, 1), newRating(b, 0)];
} else {
for (var i = 0; i < ratings.length; i++) {
var j = i;
while (j < ratings.length - 1) {
var _elo = elo([ratings[i], ratings[j + 1]], kFactor);
var _elo2 = _slicedToArray(_elo, 2);
ratings[i] = _elo2[0];
ratings[j + 1] = _elo2[1];
j++;
}
}
}
return ratings;
}; };
var escapeHTML = function escapeHTML(str) { var escapeHTML = function escapeHTML(str) {
@ -425,6 +448,22 @@ var flip = function flip(fn) {
}; };
}; };
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 (val) {
return val[1] + ' ' + (val[1] !== 1 ? val[0] + 's' : val[0]);
}).join(', ');
};
var fromCamelCase = function fromCamelCase(str) { var fromCamelCase = function fromCamelCase(str) {
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '_'; 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(); 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();
@ -437,12 +476,11 @@ var functionName = function functionName(fn) {
var gcd = function gcd() { var gcd = function gcd() {
var _ref; var _ref;
var data = (_ref = []).concat.apply(_ref, arguments); var _gcd = function _gcd(x, y) {
var helperGcd = function helperGcd(x, y) {
return !y ? x : gcd(y, x % y); return !y ? x : gcd(y, x % y);
}; };
return data.reduce(function (a, b) { return (_ref = []).concat.apply(_ref, arguments).reduce(function (a, b) {
return helperGcd(a, b); return _gcd(a, b);
}); });
}; };
@ -633,7 +671,7 @@ var isEven = function isEven(num) {
}; };
var isFunction = function isFunction(val) { var isFunction = function isFunction(val) {
return val && typeof val === 'function'; return typeof val === 'function';
}; };
var isNull = function isNull(val) { var isNull = function isNull(val) {
@ -754,6 +792,18 @@ var lowercaseKeys = function lowercaseKeys(obj) {
}, {}); }, {});
}; };
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 || 9;
}, 0);
sum += lastDigit;
return sum % 10 === 0;
};
var mapObject = function mapObject(arr, fn) { var mapObject = function mapObject(arr, fn) {
return function (a) { return function (a) {
return a = [arr, arr.map(fn)], a[0].reduce(function (acc, val, ind) { return a = [arr, arr.map(fn)], a[0].reduce(function (acc, val, ind) {
@ -905,11 +955,19 @@ var pipeFunctions = function pipeFunctions() {
}); });
}; };
var pluralize = function pluralize(num, item) { var _typeof$3 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var items = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : item + 's';
return num <= 0 ? function () { var pluralize = function pluralize(val, word) {
throw new Error('\'num\' should be >= 1. Value povided was ' + num + '.'); var plural = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : word + 's';
}() : num === 1 ? item : items;
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 === 'undefined' ? 'undefined' : _typeof$3(val)) === 'object') return function (num, word) {
return _pluralize(num, word, val[word]);
};
return _pluralize(val, word, plural);
}; };
var powerset = function powerset(arr) { var powerset = function powerset(arr) {
@ -1007,10 +1065,10 @@ var pullAtValue = function pullAtValue(arr, pullArr) {
function _toConsumableArray$10(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function _toConsumableArray$10(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
function _toArray$1(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } function _toArray$2(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
var quickSort = function quickSort(_ref, desc) { var quickSort = function quickSort(_ref, desc) {
var _ref2 = _toArray$1(_ref), var _ref2 = _toArray$2(_ref),
n = _ref2[0], n = _ref2[0],
nums = _ref2.slice(1); nums = _ref2.slice(1);
@ -1103,10 +1161,10 @@ var sample = function sample(arr) {
return arr[Math.floor(Math.random() * arr.length)]; return arr[Math.floor(Math.random() * arr.length)];
}; };
function _toArray$2(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } function _toArray$3(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
var sampleSize = function sampleSize(_ref) { var sampleSize = function sampleSize(_ref) {
var _ref2 = _toArray$2(_ref), var _ref2 = _toArray$3(_ref),
arr = _ref2.slice(0); arr = _ref2.slice(0);
var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
@ -1160,10 +1218,10 @@ var show = function show() {
}); });
}; };
function _toArray$3(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } function _toArray$4(arr) { return Array.isArray(arr) ? arr : Array.from(arr); }
var shuffle = function shuffle(_ref) { var shuffle = function shuffle(_ref) {
var _ref2 = _toArray$3(_ref), var _ref2 = _toArray$4(_ref),
arr = _ref2.slice(0); arr = _ref2.slice(0);
var m = arr.length; var m = arr.length;
@ -1182,10 +1240,10 @@ var similarity = function similarity(arr, values) {
}); });
}; };
var _typeof$3 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _typeof$4 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var size = function size(value) { var size = function size(value) {
return Array.isArray(value) ? value.length : value && (typeof value === 'undefined' ? 'undefined' : _typeof$3(value)) === 'object' ? value.size || value.length || Object.keys(value).length : typeof value === 'string' ? new Blob([value]).size : 0; return Array.isArray(value) ? value.length : value && (typeof value === 'undefined' ? 'undefined' : _typeof$4(value)) === 'object' ? value.size || value.length || Object.keys(value).length : typeof value === 'string' ? new Blob([value]).size : 0;
}; };
var sleep = function sleep(ms) { var sleep = function sleep(ms) {
@ -1456,7 +1514,7 @@ var zipObject = function zipObject(props, values) {
}, {}); }, {});
}; };
var imports = { JSONToDate: JSONToDate, JSONToFile: JSONToFile, RGBToHex: RGBToHex, UUIDGeneratorBrowser: UUIDGeneratorBrowser, UUIDGeneratorNode: UUIDGeneratorNode, anagrams: anagrams, arrayToHtmlList: arrayToHtmlList, average: average, bottomVisible: bottomVisible, byteSize: byteSize, call: call, capitalize: capitalize, capitalizeEveryWord: capitalizeEveryWord, chainAsync: chainAsync, chunk: chunk, clampNumber: clampNumber, cleanObj: cleanObj, cloneRegExp: cloneRegExp, coalesce: coalesce, coalesceFactory: coalesceFactory, collatz: collatz, collectInto: collectInto, compact: compact, compose: compose, copyToClipboard: copyToClipboard, countOccurrences: countOccurrences, countVowels: countVowels, currentURL: currentURL, curry: curry, deepFlatten: deepFlatten, defer: defer, detectDeviceType: detectDeviceType, difference: difference, differenceWith: differenceWith, digitize: digitize, distance: distance, distinctValuesOfArray: distinctValuesOfArray, dropElements: dropElements, dropRight: dropRight, elementIsVisibleInViewport: elementIsVisibleInViewport, elo: elo, escapeHTML: escapeHTML, escapeRegExp: escapeRegExp, everyNth: everyNth, extendHex: extendHex, factorial: factorial, factors: factors, fibonacci: fibonacci, fibonacciCountUntilNum: fibonacciCountUntilNum, fibonacciUntilNum: fibonacciUntilNum, filterNonUnique: filterNonUnique, flatten: flatten, flattenDepth: flattenDepth, flip: flip, fromCamelCase: fromCamelCase, functionName: functionName, gcd: gcd, geometricProgression: geometricProgression, getDaysDiffBetweenDates: getDaysDiffBetweenDates, getScrollPosition: getScrollPosition, getStyle: getStyle, getType: getType, getURLParameters: getURLParameters, groupBy: groupBy, hammingDistance: hammingDistance, hasClass: hasClass, hasFlags: hasFlags, head: head, hexToRGB: hexToRGB, hide: hide, howManyTimes: howManyTimes, httpsRedirect: httpsRedirect, inRange: inRange, initial: initial, initialize2DArray: initialize2DArray, initializeArrayWithRange: initializeArrayWithRange, initializeArrayWithValues: initializeArrayWithValues, intersection: intersection, invertKeyValues: invertKeyValues, isAbsoluteURL: isAbsoluteURL, isArmstrongNumber: isArmstrongNumber, isArray: isArray, isArrayLike: isArrayLike, isBoolean: isBoolean, isDivisible: isDivisible, isEven: isEven, isFunction: isFunction, isNull: isNull, isNumber: isNumber, isPrime: isPrime, isPrimitive: isPrimitive, isPromiseLike: isPromiseLike, isSorted: isSorted, isString: isString, isSymbol: isSymbol, isTravisCI: isTravisCI, isValidJSON: isValidJSON, join: join, last: last, lcm: lcm, lowercaseKeys: lowercaseKeys, mapObject: mapObject, mask: mask, maxN: maxN, median: median, memoize: memoize, minN: minN, negate: negate, nthElement: nthElement, objectFromPairs: objectFromPairs, objectToPairs: objectToPairs, onUserInputChange: onUserInputChange, once: once, orderBy: orderBy, palindrome: palindrome, percentile: percentile, pick: pick, pipeFunctions: pipeFunctions, pluralize: pluralize, powerset: powerset, prettyBytes: prettyBytes, primes: primes, promisify: promisify, pull: pull, pullAtIndex: pullAtIndex, pullAtValue: pullAtValue, quickSort: quickSort, randomHexColorCode: randomHexColorCode, randomIntegerInRange: randomIntegerInRange, randomNumberInRange: randomNumberInRange, readFileLines: readFileLines, redirect: redirect, reducedFilter: reducedFilter, remove: remove, repeatString: repeatString, reverseString: reverseString, round: round, runAsync: runAsync, runPromisesInSeries: runPromisesInSeries, sample: sample, sampleSize: sampleSize, scrollToTop: scrollToTop, sdbm: sdbm, select: select, setStyle: setStyle, shallowClone: shallowClone, show: show, shuffle: shuffle, similarity: similarity, size: size, sleep: sleep, solveRPN: solveRPN, sortCharactersInString: sortCharactersInString, sortedIndex: sortedIndex, speechSynthesis: speechSynthesis, splitLines: splitLines, spreadOver: spreadOver, standardDeviation: standardDeviation, sum: sum, sumPower: sumPower, symmetricDifference: symmetricDifference, tail: tail, take: take, takeRight: takeRight, timeTaken: timeTaken, toCamelCase: toCamelCase, toDecimalMark: toDecimalMark, toEnglishDate: toEnglishDate, toKebabCase: toKebabCase, toOrdinalSuffix: toOrdinalSuffix, toSnakeCase: toSnakeCase, toggleClass: toggleClass, tomorrow: tomorrow, truncateString: truncateString, truthCheckCollection: truthCheckCollection, unescapeHTML: unescapeHTML, union: union, untildify: untildify, validateNumber: validateNumber, without: without, words: words, yesNo: yesNo, zip: zip, zipObject: zipObject }; var imports = { JSONToDate: JSONToDate, JSONToFile: JSONToFile, RGBToHex: RGBToHex, UUIDGeneratorBrowser: UUIDGeneratorBrowser, UUIDGeneratorNode: UUIDGeneratorNode, anagrams: anagrams, arrayToHtmlList: arrayToHtmlList, average: average, bottomVisible: bottomVisible, byteSize: byteSize, call: call, capitalize: capitalize, capitalizeEveryWord: capitalizeEveryWord, chainAsync: chainAsync, chunk: chunk, clampNumber: clampNumber, cleanObj: cleanObj, cloneRegExp: cloneRegExp, coalesce: coalesce, coalesceFactory: coalesceFactory, collatz: collatz, collectInto: collectInto, compact: compact, compose: compose, copyToClipboard: copyToClipboard, countOccurrences: countOccurrences, countVowels: countVowels, currentURL: currentURL, curry: curry, deepFlatten: deepFlatten, defer: defer, detectDeviceType: detectDeviceType, difference: difference, differenceWith: differenceWith, digitize: digitize, distance: distance, distinctValuesOfArray: distinctValuesOfArray, dropElements: dropElements, dropRight: dropRight, elementIsVisibleInViewport: elementIsVisibleInViewport, elo: elo, escapeHTML: escapeHTML, escapeRegExp: escapeRegExp, everyNth: everyNth, extendHex: extendHex, factorial: factorial, factors: factors, fibonacci: fibonacci, fibonacciCountUntilNum: fibonacciCountUntilNum, fibonacciUntilNum: fibonacciUntilNum, filterNonUnique: filterNonUnique, flatten: flatten, flattenDepth: flattenDepth, flip: flip, formatDuration: formatDuration, fromCamelCase: fromCamelCase, functionName: functionName, gcd: gcd, geometricProgression: geometricProgression, getDaysDiffBetweenDates: getDaysDiffBetweenDates, getScrollPosition: getScrollPosition, getStyle: getStyle, getType: getType, getURLParameters: getURLParameters, groupBy: groupBy, hammingDistance: hammingDistance, hasClass: hasClass, hasFlags: hasFlags, head: head, hexToRGB: hexToRGB, hide: hide, howManyTimes: howManyTimes, httpsRedirect: httpsRedirect, inRange: inRange, initial: initial, initialize2DArray: initialize2DArray, initializeArrayWithRange: initializeArrayWithRange, initializeArrayWithValues: initializeArrayWithValues, intersection: intersection, invertKeyValues: invertKeyValues, isAbsoluteURL: isAbsoluteURL, isArmstrongNumber: isArmstrongNumber, isArray: isArray, isArrayLike: isArrayLike, isBoolean: isBoolean, isDivisible: isDivisible, isEven: isEven, isFunction: isFunction, isNull: isNull, isNumber: isNumber, isPrime: isPrime, isPrimitive: isPrimitive, isPromiseLike: isPromiseLike, isSorted: isSorted, isString: isString, isSymbol: isSymbol, isTravisCI: isTravisCI, isValidJSON: isValidJSON, join: join, last: last, lcm: lcm, lowercaseKeys: lowercaseKeys, luhnCheck: luhnCheck, mapObject: mapObject, mask: mask, maxN: maxN, median: median, memoize: memoize, minN: minN, negate: negate, nthElement: nthElement, objectFromPairs: objectFromPairs, objectToPairs: objectToPairs, onUserInputChange: onUserInputChange, once: once, orderBy: orderBy, palindrome: palindrome, percentile: percentile, pick: pick, pipeFunctions: pipeFunctions, pluralize: pluralize, powerset: powerset, prettyBytes: prettyBytes, primes: primes, promisify: promisify, pull: pull, pullAtIndex: pullAtIndex, pullAtValue: pullAtValue, quickSort: quickSort, randomHexColorCode: randomHexColorCode, randomIntegerInRange: randomIntegerInRange, randomNumberInRange: randomNumberInRange, readFileLines: readFileLines, redirect: redirect, reducedFilter: reducedFilter, remove: remove, repeatString: repeatString, reverseString: reverseString, round: round, runAsync: runAsync, runPromisesInSeries: runPromisesInSeries, sample: sample, sampleSize: sampleSize, scrollToTop: scrollToTop, sdbm: sdbm, select: select, setStyle: setStyle, shallowClone: shallowClone, show: show, shuffle: shuffle, similarity: similarity, size: size, sleep: sleep, solveRPN: solveRPN, sortCharactersInString: sortCharactersInString, sortedIndex: sortedIndex, speechSynthesis: speechSynthesis, splitLines: splitLines, spreadOver: spreadOver, standardDeviation: standardDeviation, sum: sum, sumPower: sumPower, symmetricDifference: symmetricDifference, tail: tail, take: take, takeRight: takeRight, timeTaken: timeTaken, toCamelCase: toCamelCase, toDecimalMark: toDecimalMark, toEnglishDate: toEnglishDate, toKebabCase: toKebabCase, toOrdinalSuffix: toOrdinalSuffix, toSnakeCase: toSnakeCase, toggleClass: toggleClass, tomorrow: tomorrow, truncateString: truncateString, truthCheckCollection: truthCheckCollection, unescapeHTML: unescapeHTML, union: union, untildify: untildify, validateNumber: validateNumber, without: without, words: words, yesNo: yesNo, zip: zip, zipObject: zipObject };
return imports; return imports;

File diff suppressed because one or more lines are too long

68
dist/_30s.esm.js vendored
View File

@ -131,7 +131,7 @@ const difference = (a, b) => {
return a.filter(x => !s.has(x)); return a.filter(x => !s.has(x));
}; };
const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b))); const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
const digitize = n => [...('' + n)].map(i => parseInt(i)); const digitize = n => [...('' + n)].map(i => parseInt(i));
@ -155,10 +155,23 @@ const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}; };
const elo = ([a, b], kFactor = 32) => { const elo = ([...ratings], kFactor = 32, selfRating) => {
const [a, b] = ratings;
const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400)); const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400));
const newRating = (rating, i) => rating + kFactor * (i - expectedScore(i ? a : b, i ? b : a)); const newRating = (rating, i) =>
return [newRating(a, 1), newRating(b, 0)]; (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a));
if (ratings.length === 2) {
return [newRating(a, 1), newRating(b, 0)];
} else {
for (let i = 0; i < ratings.length; i++) {
let j = i;
while (j < ratings.length - 1) {
[ratings[i], ratings[j + 1]] = elo([ratings[i], ratings[j + 1]], kFactor);
j++;
}
}
}
return ratings;
}; };
const escapeHTML = str => const escapeHTML = str =>
@ -241,6 +254,21 @@ const flattenDepth = (arr, depth = 1) =>
const flip = fn => (...args) => fn(args.pop(), ...args); const flip = fn => (...args) => fn(args.pop(), ...args);
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(val => val[1] + ' ' + (val[1] !== 1 ? val[0] + 's' : val[0]))
.join(', ');
};
const fromCamelCase = (str, separator = '_') => const fromCamelCase = (str, separator = '_') =>
str str
.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
@ -250,9 +278,8 @@ const fromCamelCase = (str, separator = '_') =>
const functionName = fn => (console.debug(fn.name), fn); const functionName = fn => (console.debug(fn.name), fn);
const gcd = (...arr) => { const gcd = (...arr) => {
let data = [].concat(...arr); const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
const helperGcd = (x, y) => (!y ? x : gcd(y, x % y)); return [].concat(...arr).reduce((a, b) => _gcd(a, b));
return data.reduce((a, b) => helperGcd(a, b));
}; };
const geometricProgression = (end, start = 1, step = 2) => const geometricProgression = (end, start = 1, step = 2) =>
@ -381,7 +408,7 @@ const isDivisible = (dividend, divisor) => dividend % divisor === 0;
const isEven = num => num % 2 === 0; const isEven = num => num % 2 === 0;
const isFunction = val => val && typeof val === 'function'; const isFunction = val => typeof val === 'function';
const isNull = val => val === null; const isNull = val => val === null;
@ -445,6 +472,17 @@ const lowercaseKeys = obj =>
return acc; return acc;
}, {}); }, {});
const luhnCheck = num => {
let arr = (num + '')
.split('')
.reverse()
.map(x => parseInt(x));
let lastDigit = arr.splice(0, 1)[0];
let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + (val * 2) % 9 || 9), 0);
sum += lastDigit;
return sum % 10 === 0;
};
const mapObject = (arr, fn) => const mapObject = (arr, fn) =>
(a => ( (a => (
a = [arr, arr.map(fn)], a[0].reduce((acc, val, ind) => (acc[val] = a[1][ind], acc), {})))(); a = [arr, arr.map(fn)], a[0].reduce((acc, val, ind) => (acc[val] = a[1][ind], acc), {})))();
@ -533,12 +571,12 @@ const pick = (obj, arr) =>
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
const pluralize = (num, item, items = item + 's') => const pluralize = (val, word, plural = word + 's') => {
num <= 0 const _pluralize = (num, word, plural = word + 's') =>
? (() => { [1, -1].includes(Number(num)) ? word : plural;
throw new Error(`'num' should be >= 1. Value povided was ${num}.`); if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]);
})() return _pluralize(val, word, plural);
: num === 1 ? item : items; };
const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);
@ -898,6 +936,6 @@ const zip = (...arrays) => {
const zipObject = (props, values) => const zipObject = (props, values) =>
props.reduce((obj, prop, index) => (obj[prop] = values[index], obj), {}); props.reduce((obj, prop, index) => (obj[prop] = values[index], obj), {});
var imports = {JSONToDate,JSONToFile,RGBToHex,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,average,bottomVisible,byteSize,call,capitalize,capitalizeEveryWord,chainAsync,chunk,clampNumber,cleanObj,cloneRegExp,coalesce,coalesceFactory,collatz,collectInto,compact,compose,copyToClipboard,countOccurrences,countVowels,currentURL,curry,deepFlatten,defer,detectDeviceType,difference,differenceWith,digitize,distance,distinctValuesOfArray,dropElements,dropRight,elementIsVisibleInViewport,elo,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,factors,fibonacci,fibonacciCountUntilNum,fibonacciUntilNum,filterNonUnique,flatten,flattenDepth,flip,fromCamelCase,functionName,gcd,geometricProgression,getDaysDiffBetweenDates,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,head,hexToRGB,hide,howManyTimes,httpsRedirect,inRange,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithValues,intersection,invertKeyValues,isAbsoluteURL,isArmstrongNumber,isArray,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isNull,isNumber,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isValidJSON,join,last,lcm,lowercaseKeys,mapObject,mask,maxN,median,memoize,minN,negate,nthElement,objectFromPairs,objectToPairs,onUserInputChange,once,orderBy,palindrome,percentile,pick,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,quickSort,randomHexColorCode,randomIntegerInRange,randomNumberInRange,readFileLines,redirect,reducedFilter,remove,repeatString,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,select,setStyle,shallowClone,show,shuffle,similarity,size,sleep,solveRPN,sortCharactersInString,sortedIndex,speechSynthesis,splitLines,spreadOver,standardDeviation,sum,sumPower,symmetricDifference,tail,take,takeRight,timeTaken,toCamelCase,toDecimalMark,toEnglishDate,toKebabCase,toOrdinalSuffix,toSnakeCase,toggleClass,tomorrow,truncateString,truthCheckCollection,unescapeHTML,union,untildify,validateNumber,without,words,yesNo,zip,zipObject,} var imports = {JSONToDate,JSONToFile,RGBToHex,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,average,bottomVisible,byteSize,call,capitalize,capitalizeEveryWord,chainAsync,chunk,clampNumber,cleanObj,cloneRegExp,coalesce,coalesceFactory,collatz,collectInto,compact,compose,copyToClipboard,countOccurrences,countVowels,currentURL,curry,deepFlatten,defer,detectDeviceType,difference,differenceWith,digitize,distance,distinctValuesOfArray,dropElements,dropRight,elementIsVisibleInViewport,elo,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,factors,fibonacci,fibonacciCountUntilNum,fibonacciUntilNum,filterNonUnique,flatten,flattenDepth,flip,formatDuration,fromCamelCase,functionName,gcd,geometricProgression,getDaysDiffBetweenDates,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,head,hexToRGB,hide,howManyTimes,httpsRedirect,inRange,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithValues,intersection,invertKeyValues,isAbsoluteURL,isArmstrongNumber,isArray,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isNull,isNumber,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isValidJSON,join,last,lcm,lowercaseKeys,luhnCheck,mapObject,mask,maxN,median,memoize,minN,negate,nthElement,objectFromPairs,objectToPairs,onUserInputChange,once,orderBy,palindrome,percentile,pick,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,quickSort,randomHexColorCode,randomIntegerInRange,randomNumberInRange,readFileLines,redirect,reducedFilter,remove,repeatString,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,select,setStyle,shallowClone,show,shuffle,similarity,size,sleep,solveRPN,sortCharactersInString,sortedIndex,speechSynthesis,splitLines,spreadOver,standardDeviation,sum,sumPower,symmetricDifference,tail,take,takeRight,timeTaken,toCamelCase,toDecimalMark,toEnglishDate,toKebabCase,toOrdinalSuffix,toSnakeCase,toggleClass,tomorrow,truncateString,truthCheckCollection,unescapeHTML,union,untildify,validateNumber,without,words,yesNo,zip,zipObject,}
export default imports; export default imports;

68
dist/_30s.js vendored
View File

@ -137,7 +137,7 @@ const difference = (a, b) => {
return a.filter(x => !s.has(x)); return a.filter(x => !s.has(x));
}; };
const differenceWith = (arr, val, comp) => arr.filter(a => !val.find(b => comp(a, b))); const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
const digitize = n => [...('' + n)].map(i => parseInt(i)); const digitize = n => [...('' + n)].map(i => parseInt(i));
@ -161,10 +161,23 @@ const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}; };
const elo = ([a, b], kFactor = 32) => { const elo = ([...ratings], kFactor = 32, selfRating) => {
const [a, b] = ratings;
const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400)); const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400));
const newRating = (rating, i) => rating + kFactor * (i - expectedScore(i ? a : b, i ? b : a)); const newRating = (rating, i) =>
return [newRating(a, 1), newRating(b, 0)]; (selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a));
if (ratings.length === 2) {
return [newRating(a, 1), newRating(b, 0)];
} else {
for (let i = 0; i < ratings.length; i++) {
let j = i;
while (j < ratings.length - 1) {
[ratings[i], ratings[j + 1]] = elo([ratings[i], ratings[j + 1]], kFactor);
j++;
}
}
}
return ratings;
}; };
const escapeHTML = str => const escapeHTML = str =>
@ -247,6 +260,21 @@ const flattenDepth = (arr, depth = 1) =>
const flip = fn => (...args) => fn(args.pop(), ...args); const flip = fn => (...args) => fn(args.pop(), ...args);
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(val => val[1] + ' ' + (val[1] !== 1 ? val[0] + 's' : val[0]))
.join(', ');
};
const fromCamelCase = (str, separator = '_') => const fromCamelCase = (str, separator = '_') =>
str str
.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
@ -256,9 +284,8 @@ const fromCamelCase = (str, separator = '_') =>
const functionName = fn => (console.debug(fn.name), fn); const functionName = fn => (console.debug(fn.name), fn);
const gcd = (...arr) => { const gcd = (...arr) => {
let data = [].concat(...arr); const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
const helperGcd = (x, y) => (!y ? x : gcd(y, x % y)); return [].concat(...arr).reduce((a, b) => _gcd(a, b));
return data.reduce((a, b) => helperGcd(a, b));
}; };
const geometricProgression = (end, start = 1, step = 2) => const geometricProgression = (end, start = 1, step = 2) =>
@ -387,7 +414,7 @@ const isDivisible = (dividend, divisor) => dividend % divisor === 0;
const isEven = num => num % 2 === 0; const isEven = num => num % 2 === 0;
const isFunction = val => val && typeof val === 'function'; const isFunction = val => typeof val === 'function';
const isNull = val => val === null; const isNull = val => val === null;
@ -451,6 +478,17 @@ const lowercaseKeys = obj =>
return acc; return acc;
}, {}); }, {});
const luhnCheck = num => {
let arr = (num + '')
.split('')
.reverse()
.map(x => parseInt(x));
let lastDigit = arr.splice(0, 1)[0];
let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + (val * 2) % 9 || 9), 0);
sum += lastDigit;
return sum % 10 === 0;
};
const mapObject = (arr, fn) => const mapObject = (arr, fn) =>
(a => ( (a => (
a = [arr, arr.map(fn)], a[0].reduce((acc, val, ind) => (acc[val] = a[1][ind], acc), {})))(); a = [arr, arr.map(fn)], a[0].reduce((acc, val, ind) => (acc[val] = a[1][ind], acc), {})))();
@ -539,12 +577,12 @@ const pick = (obj, arr) =>
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
const pluralize = (num, item, items = item + 's') => const pluralize = (val, word, plural = word + 's') => {
num <= 0 const _pluralize = (num, word, plural = word + 's') =>
? (() => { [1, -1].includes(Number(num)) ? word : plural;
throw new Error(`'num' should be >= 1. Value povided was ${num}.`); if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]);
})() return _pluralize(val, word, plural);
: num === 1 ? item : items; };
const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);
@ -904,7 +942,7 @@ const zip = (...arrays) => {
const zipObject = (props, values) => const zipObject = (props, values) =>
props.reduce((obj, prop, index) => (obj[prop] = values[index], obj), {}); props.reduce((obj, prop, index) => (obj[prop] = values[index], obj), {});
var imports = {JSONToDate,JSONToFile,RGBToHex,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,average,bottomVisible,byteSize,call,capitalize,capitalizeEveryWord,chainAsync,chunk,clampNumber,cleanObj,cloneRegExp,coalesce,coalesceFactory,collatz,collectInto,compact,compose,copyToClipboard,countOccurrences,countVowels,currentURL,curry,deepFlatten,defer,detectDeviceType,difference,differenceWith,digitize,distance,distinctValuesOfArray,dropElements,dropRight,elementIsVisibleInViewport,elo,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,factors,fibonacci,fibonacciCountUntilNum,fibonacciUntilNum,filterNonUnique,flatten,flattenDepth,flip,fromCamelCase,functionName,gcd,geometricProgression,getDaysDiffBetweenDates,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,head,hexToRGB,hide,howManyTimes,httpsRedirect,inRange,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithValues,intersection,invertKeyValues,isAbsoluteURL,isArmstrongNumber,isArray,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isNull,isNumber,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isValidJSON,join,last,lcm,lowercaseKeys,mapObject,mask,maxN,median,memoize,minN,negate,nthElement,objectFromPairs,objectToPairs,onUserInputChange,once,orderBy,palindrome,percentile,pick,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,quickSort,randomHexColorCode,randomIntegerInRange,randomNumberInRange,readFileLines,redirect,reducedFilter,remove,repeatString,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,select,setStyle,shallowClone,show,shuffle,similarity,size,sleep,solveRPN,sortCharactersInString,sortedIndex,speechSynthesis,splitLines,spreadOver,standardDeviation,sum,sumPower,symmetricDifference,tail,take,takeRight,timeTaken,toCamelCase,toDecimalMark,toEnglishDate,toKebabCase,toOrdinalSuffix,toSnakeCase,toggleClass,tomorrow,truncateString,truthCheckCollection,unescapeHTML,union,untildify,validateNumber,without,words,yesNo,zip,zipObject,} var imports = {JSONToDate,JSONToFile,RGBToHex,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,average,bottomVisible,byteSize,call,capitalize,capitalizeEveryWord,chainAsync,chunk,clampNumber,cleanObj,cloneRegExp,coalesce,coalesceFactory,collatz,collectInto,compact,compose,copyToClipboard,countOccurrences,countVowels,currentURL,curry,deepFlatten,defer,detectDeviceType,difference,differenceWith,digitize,distance,distinctValuesOfArray,dropElements,dropRight,elementIsVisibleInViewport,elo,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,factors,fibonacci,fibonacciCountUntilNum,fibonacciUntilNum,filterNonUnique,flatten,flattenDepth,flip,formatDuration,fromCamelCase,functionName,gcd,geometricProgression,getDaysDiffBetweenDates,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,head,hexToRGB,hide,howManyTimes,httpsRedirect,inRange,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithValues,intersection,invertKeyValues,isAbsoluteURL,isArmstrongNumber,isArray,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isNull,isNumber,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isValidJSON,join,last,lcm,lowercaseKeys,luhnCheck,mapObject,mask,maxN,median,memoize,minN,negate,nthElement,objectFromPairs,objectToPairs,onUserInputChange,once,orderBy,palindrome,percentile,pick,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,quickSort,randomHexColorCode,randomIntegerInRange,randomNumberInRange,readFileLines,redirect,reducedFilter,remove,repeatString,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,select,setStyle,shallowClone,show,shuffle,similarity,size,sleep,solveRPN,sortCharactersInString,sortedIndex,speechSynthesis,splitLines,spreadOver,standardDeviation,sum,sumPower,symmetricDifference,tail,take,takeRight,timeTaken,toCamelCase,toDecimalMark,toEnglishDate,toKebabCase,toOrdinalSuffix,toSnakeCase,toggleClass,tomorrow,truncateString,truthCheckCollection,unescapeHTML,union,untildify,validateNumber,without,words,yesNo,zip,zipObject,}
return imports; return imports;

2
dist/_30s.min.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -131,6 +131,8 @@ $_drawer-right: false;
@import 'navigation'; @import 'navigation';
$mark-back-color: #424242;
$mark-font-size: 0.5em;
$toast-back-color: #212121; $toast-back-color: #212121;
@ -163,6 +165,12 @@ $_include-collapse: false;
transition: opacity 0.3s ease-in-out; transition: opacity 0.3s ease-in-out;
} }
mark {
position: relative;
top: -0.25rem;
left: 0.25rem;
}
/* /*
Custom elements for contextual background elements, toasts and tooltips. Custom elements for contextual background elements, toasts and tooltips.
*/ */
@ -318,7 +326,7 @@ button.primary.clipboard-copy {
code[class*="language-"], code[class*="language-"],
pre[class*="language-"] { pre[class*="language-"] {
color: black; color: #222;
text-align: left; text-align: left;
white-space: pre; white-space: pre;
word-spacing: normal; word-spacing: normal;
@ -385,8 +393,9 @@ code[class*="language-"]::selection, code[class*="language-"] ::selection {
} }
.token.number{ .token.number,
color: #8132b5; .token.class-name {
color: #832ed2;
} }
.token.selector, .token.selector,
@ -395,7 +404,7 @@ code[class*="language-"]::selection, code[class*="language-"] ::selection {
.token.char, .token.char,
.token.builtin, .token.builtin,
.token.inserted { .token.inserted {
color: #007e5d; color: #067e36;
} }
.token.operator, .token.operator,
@ -410,7 +419,7 @@ code[class*="language-"]::selection, code[class*="language-"] ::selection {
} }
.token.regex { .token.regex {
color: #007972; color: #097cab;
} }
.token.important, .token.important,
.token.variable { .token.variable {

View File

@ -73,7 +73,11 @@ try {
.readFileSync('tag_database', 'utf8') .readFileSync('tag_database', 'utf8')
.split('\n') .split('\n')
.slice(0, -1) .slice(0, -1)
.map(v => v.split(':').slice(0, 2)) .map(v => {
let data = v.split(':').slice(0, 2);
data[1] = data[1].split(',').map(t => t.trim());
return data;
})
); );
} catch (err) { } catch (err) {
console.log(`${chalk.red('ERROR!')} During tag database loading: ${err}`); console.log(`${chalk.red('ERROR!')} During tag database loading: ${err}`);
@ -85,7 +89,7 @@ try {
const tags = [ const tags = [
...new Set( ...new Set(
Object.entries(tagDbData) Object.entries(tagDbData)
.map(t => t[1]) .map(t => t[1][0])
.filter(v => v) .filter(v => v)
.sort((a, b) => a.localeCompare(b)) .sort((a, b) => a.localeCompare(b))
) )
@ -101,16 +105,16 @@ try {
if (capitalizedTag === 'Uncategorized') { if (capitalizedTag === 'Uncategorized') {
uncategorizedOutput += `### _${capitalizedTag}_\n\n<details>\n<summary>View contents</summary>\n\n`; uncategorizedOutput += `### _${capitalizedTag}_\n\n<details>\n<summary>View contents</summary>\n\n`;
for (const taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag)) { for (const taggedSnippet of Object.entries(tagDbData).filter(v => v[1][0] === tag)) {
uncategorizedOutput += `* [\`${taggedSnippet[0]}\`](#${taggedSnippet[0].toLowerCase()})\n`; uncategorizedOutput += `* [\`${taggedSnippet[0]}\`](#${taggedSnippet[0].toLowerCase()}${taggedSnippet[1].includes('advanced')?'-':''})\n`;
} }
uncategorizedOutput += '\n</details>\n\n'; uncategorizedOutput += '\n</details>\n\n';
} else { } else {
output += `### ${ output += `### ${
EMOJIS[tag] || '' EMOJIS[tag] || ''
} ${capitalizedTag}\n\n<details>\n<summary>View contents</summary>\n\n`; } ${capitalizedTag}\n\n<details>\n<summary>View contents</summary>\n\n`;
for (const taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag)) { for (const taggedSnippet of Object.entries(tagDbData).filter(v => v[1][0] === tag)) {
output += `* [\`${taggedSnippet[0]}\`](#${taggedSnippet[0].toLowerCase()})\n`; output += `* [\`${taggedSnippet[0]}\`](#${taggedSnippet[0].toLowerCase()}${taggedSnippet[1].includes('advanced')?'-':''})\n`;
} }
output += '\n</details>\n\n'; output += '\n</details>\n\n';
} }
@ -122,17 +126,23 @@ try {
// Loop over tags and snippets to create the list of snippets // Loop over tags and snippets to create the list of snippets
for (const tag of tags) { for (const tag of tags) {
const capitalizedTag = capitalize(tag, true); const capitalizedTag = capitalize(tag, true);
// ![advanced](/advanced.svg)
if (capitalizedTag == 'Uncategorized') { if (capitalizedTag == 'Uncategorized') {
uncategorizedOutput += `---\n ## _${capitalizedTag}_\n`; uncategorizedOutput += `---\n ## _${capitalizedTag}_\n`;
for (const taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag)) { for (const taggedSnippet of Object.entries(tagDbData).filter(v => v[1][0] === tag)) {
uncategorizedOutput += `\n${snippets[taggedSnippet[0] + '.md'] + uncategorizedOutput += `\n${snippets[taggedSnippet[0] + '.md'] +
'\n<br>[⬆ back to top](#table-of-contents)\n\n'}`; '\n<br>[⬆ back to top](#table-of-contents)\n\n'}`;
} }
} else { } else {
output += `---\n ## ${EMOJIS[tag] || ''} ${capitalizedTag}\n`; output += `---\n ## ${EMOJIS[tag] || ''} ${capitalizedTag}\n`;
for (const taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag)) { for (const taggedSnippet of Object.entries(tagDbData).filter(v => v[1][0] === tag)) {
let data = snippets[taggedSnippet[0] + '.md']; let data = snippets[taggedSnippet[0] + '.md'];
// Add advanced tag
if(taggedSnippet[1].includes('advanced')){
data = data.split(/\r?\n/);
data[0] = data[0] +' ![advanced](/advanced.svg)';
data = data.join('\n');
}
data = data =
data.slice(0, data.lastIndexOf('```js')) + data.slice(0, data.lastIndexOf('```js')) +
'<details>\n<summary>Examples</summary>\n\n' + '<details>\n<summary>Examples</summary>\n\n' +

View File

@ -50,10 +50,14 @@ try {
.readFileSync('tag_database', 'utf8') .readFileSync('tag_database', 'utf8')
.split('\n') .split('\n')
.slice(0, -1) .slice(0, -1)
.map(v => v.split(':').slice(0, 2)) .map(v => {
let data = v.split(':').slice(0, 2);
data[1] = data[1].split(',').map(t => t.trim());
return data;
})
); );
tagDbStats = Object.entries(tagDbData) tagDbStats = Object.entries(tagDbData)
.sort((a, b) => a[1].localeCompare(b[1])) .sort((a, b) => a[1][0].localeCompare(b[1][0]))
.reduce((acc, val) => { .reduce((acc, val) => {
acc.hasOwnProperty(val[1]) ? acc[val[1]]++ : (acc[val[1]] = 1); acc.hasOwnProperty(val[1]) ? acc[val[1]]++ : (acc[val[1]] = 1);
return acc; return acc;
@ -68,9 +72,9 @@ try {
for (let snippet of Object.entries(snippets)) for (let snippet of Object.entries(snippets))
if ( if (
tagDbData.hasOwnProperty(snippet[0].slice(0, -3)) && tagDbData.hasOwnProperty(snippet[0].slice(0, -3)) &&
tagDbData[snippet[0].slice(0, -3)].trim() tagDbData[snippet[0].slice(0, -3)].join(',').trim()
) )
output += `${snippet[0].slice(0, -3)}:${tagDbData[snippet[0].slice(0, -3)].trim()}\n`; output += `${snippet[0].slice(0, -3)}:${tagDbData[snippet[0].slice(0, -3)].join(',').trim()}\n`;
else { else {
output += `${snippet[0].slice(0, -3)}:uncategorized\n`; output += `${snippet[0].slice(0, -3)}:uncategorized\n`;
missingTags++; missingTags++;

View File

@ -61,7 +61,7 @@ const objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {});
const capitalize = (str, lowerRest = false) => const capitalize = (str, lowerRest = false) =>
str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1)); str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));
// Start the timer of the script // Start the timer of the script
console.time('Builder'); console.time('Webber');
// Synchronously read all snippets and sort them as necessary (case-insensitive) // Synchronously read all snippets and sort them as necessary (case-insensitive)
try { try {
let snippetFilenames = fs.readdirSync(snippetsPath); let snippetFilenames = fs.readdirSync(snippetsPath);
@ -96,7 +96,11 @@ try {
.readFileSync('tag_database', 'utf8') .readFileSync('tag_database', 'utf8')
.split('\n') .split('\n')
.slice(0, -1) .slice(0, -1)
.map(v => v.split(':').slice(0, 2)) .map(v => {
let data = v.split(':').slice(0, 2);
data[1] = data[1].split(',').map(t => t.trim());
return data;
})
); );
} catch (err) { } catch (err) {
// Handle errors (hopefully not!) // Handle errors (hopefully not!)
@ -109,7 +113,7 @@ try {
output += `${startPart + '\n'}`; output += `${startPart + '\n'}`;
let uncategorizedOutput = ''; let uncategorizedOutput = '';
// Loop over tags and snippets to create the table of contents // Loop over tags and snippets to create the table of contents
for (let tag of [...new Set(Object.entries(tagDbData).map(t => t[1]))] for (let tag of [...new Set(Object.entries(tagDbData).map(t => t[1][0]))]
.filter(v => v) .filter(v => v)
.sort((a, b) => a.localeCompare(b))) { .sort((a, b) => a.localeCompare(b))) {
if (capitalize(tag, true) == 'Uncategorized') { if (capitalize(tag, true) == 'Uncategorized') {
@ -120,12 +124,12 @@ try {
.replace(/<p>/g, '') .replace(/<p>/g, '')
.replace(/<\/p>/g, '') + .replace(/<\/p>/g, '') +
`</h3>`; `</h3>`;
for (let taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag)) for (let taggedSnippet of Object.entries(tagDbData).filter(v => v[1][0] === tag))
uncategorizedOutput += md uncategorizedOutput += md
.render(`[${taggedSnippet[0]}](#${taggedSnippet[0].toLowerCase()})\n`) .render(`[${taggedSnippet[0]}](#${taggedSnippet[0].toLowerCase()})\n`)
.replace(/<p>/g, '') .replace(/<p>/g, '')
.replace(/<\/p>/g, '') .replace(/<\/p>/g, '')
.replace(/<a/g, '<a class="sublink-1"'); .replace(/<a/g, `<a class="sublink-1" tags="${taggedSnippet[1].join(',')}"`);
uncategorizedOutput += '\n'; uncategorizedOutput += '\n';
} else { } else {
output += output +=
@ -135,12 +139,12 @@ try {
.replace(/<p>/g, '') .replace(/<p>/g, '')
.replace(/<\/p>/g, '') + .replace(/<\/p>/g, '') +
`</h3>`; `</h3>`;
for (let taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag)) for (let taggedSnippet of Object.entries(tagDbData).filter(v => v[1][0] === tag))
output += md output += md
.render(`[${taggedSnippet[0]}](#${taggedSnippet[0].toLowerCase()})\n`) .render(`[${taggedSnippet[0]}](#${taggedSnippet[0].toLowerCase()})\n`)
.replace(/<p>/g, '') .replace(/<p>/g, '')
.replace(/<\/p>/g, '') .replace(/<\/p>/g, '')
.replace(/<a/g, '<a class="sublink-1"'); .replace(/<a/g, `<a class="sublink-1" tags="${taggedSnippet[1].join(',')}"`);
output += '\n'; output += '\n';
} }
} }
@ -149,19 +153,20 @@ try {
output += `<a id="top">&nbsp;</a>`; output += `<a id="top">&nbsp;</a>`;
uncategorizedOutput = ''; uncategorizedOutput = '';
// Loop over tags and snippets to create the list of snippets // Loop over tags and snippets to create the list of snippets
for (let tag of [...new Set(Object.entries(tagDbData).map(t => t[1]))] for (let tag of [...new Set(Object.entries(tagDbData).map(t => t[1][0]))]
.filter(v => v) .filter(v => v)
.sort((a, b) => a.localeCompare(b))) { .sort((a, b) => a.localeCompare(b))) {
if (capitalize(tag, true) == 'Uncategorized') { if (capitalize(tag, true) == 'Uncategorized') {
uncategorizedOutput += md uncategorizedOutput += md
.render(`## ${capitalize(tag, true)}\n`) .render(`## ${capitalize(tag, true)}\n`)
.replace(/<h2>/g, '<h2 style="text-align:center;">'); .replace(/<h2>/g, '<h2 style="text-align:center;">');
for (let taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag)) for (let taggedSnippet of Object.entries(tagDbData).filter(v => v[1][0] === tag))
uncategorizedOutput += uncategorizedOutput +=
'<div class="card fluid">' + '<div class="card fluid">' +
md md
.render(`\n${snippets[taggedSnippet[0] + '.md']}`) .render(`\n${snippets[taggedSnippet[0] + '.md']}`)
.replace(/<h3/g, `<h3 id="${taggedSnippet[0].toLowerCase()}" class="section double-padded"`) .replace(/<h3/g, `<h3 id="${taggedSnippet[0].toLowerCase()}" class="section double-padded"`)
.replace(/<\/h3>/g, `${taggedSnippet[1].includes('advanced')?'<mark class="tag">advanced</mark>':''}</h3>`)
.replace(/<pre><code class="language-js">([^\0]*?)<\/code><\/pre>/gm, (match, p1) => `<pre class="language-js">${Prism.highlight(unescapeHTML(p1), Prism.languages.javascript)}</pre>`) .replace(/<pre><code class="language-js">([^\0]*?)<\/code><\/pre>/gm, (match, p1) => `<pre class="language-js">${Prism.highlight(unescapeHTML(p1), Prism.languages.javascript)}</pre>`)
.replace(/<\/pre>\s+<pre/g, '</pre><label class="collapse">Show examples</label><pre') + .replace(/<\/pre>\s+<pre/g, '</pre><label class="collapse">Show examples</label><pre') +
'<button class="primary clipboard-copy"><img src="clipboard.svg" alt="clipboard">&nbsp;Copy to clipboard</button>' + '<button class="primary clipboard-copy"><img src="clipboard.svg" alt="clipboard">&nbsp;Copy to clipboard</button>' +
@ -170,12 +175,13 @@ try {
output += md output += md
.render(`## ${capitalize(tag, true)}\n`) .render(`## ${capitalize(tag, true)}\n`)
.replace(/<h2>/g, '<h2 style="text-align:center;">'); .replace(/<h2>/g, '<h2 style="text-align:center;">');
for (let taggedSnippet of Object.entries(tagDbData).filter(v => v[1] === tag)) for (let taggedSnippet of Object.entries(tagDbData).filter(v => v[1][0] === tag))
output += output +=
'<div class="card fluid">' + '<div class="card fluid">' +
md md
.render(`\n${snippets[taggedSnippet[0] + '.md']}`) .render(`\n${snippets[taggedSnippet[0] + '.md']}`)
.replace(/<h3/g, `<h3 id="${taggedSnippet[0].toLowerCase()}" class="section double-padded"`) .replace(/<h3/g, `<h3 id="${taggedSnippet[0].toLowerCase()}" class="section double-padded"`)
.replace(/<\/h3>/g, `${taggedSnippet[1].includes('advanced')?'<mark class="tag">advanced</mark>':''}</h3>`)
.replace(/<\/h3>/g, '</h3><div class="section double-padded">') .replace(/<\/h3>/g, '</h3><div class="section double-padded">')
.replace(/<pre><code class="language-js">([^\0]*?)<\/code><\/pre>/gm, (match, p1) => `<pre class="language-js">${Prism.highlight(unescapeHTML(p1), Prism.languages.javascript)}</pre>`) .replace(/<pre><code class="language-js">([^\0]*?)<\/code><\/pre>/gm, (match, p1) => `<pre class="language-js">${Prism.highlight(unescapeHTML(p1), Prism.languages.javascript)}</pre>`)
.replace(/<\/pre>\s+<pre/g, '</pre><label class="collapse">Show examples</label><pre') + .replace(/<\/pre>\s+<pre/g, '</pre><label class="collapse">Show examples</label><pre') +
@ -247,4 +253,4 @@ try {
// Log a success message // Log a success message
console.log(`${chalk.green('SUCCESS!')} index.html file generated!`); console.log(`${chalk.green('SUCCESS!')} index.html file generated!`);
// Log the time taken // Log the time taken
console.timeEnd('Builder'); console.timeEnd('Webber');

View File

@ -2,7 +2,7 @@
Converts the values of RGB components to a color code. Converts the values of RGB components to a color code.
Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `padStart(6,'0')` to get a 6-digit hexadecimal value. Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `String.padStart(6,'0')` to get a 6-digit hexadecimal value.
```js ```js
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');

View File

@ -1,17 +1,14 @@
### average ### average
Returns the average of an of two or more numbers/arrays. Returns the average of an of two or more numbers.
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array. Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array.
```js ```js
const average = (...arr) => { const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length;
const nums = [].concat(...arr);
return nums.reduce((acc, val) => acc + val, 0) / nums.length;
};
``` ```
```js ```js
average([1, 2, 3]); // 2 average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2 average(1, 2, 3); // 2
``` ```

View File

@ -1,6 +1,6 @@
### byteSize ### byteSize
Returns the length of string. Returns the length of a string in bytes.
Convert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and find its `size`. Convert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and find its `size`.

View File

@ -2,7 +2,7 @@
Capitalizes the first letter of a string. Capitalizes the first letter of a string.
Use destructuring and `toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again. Use array destructuring and `String.toUpperCase()` to capitalize first letter, `...rest` to get array of characters after first letter and then `Array.join('')` to make it a string again.
Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase. Omit the `lowerRest` parameter to keep the rest of the string intact, or set it to `true` to convert to lowercase.
```js ```js

View File

@ -2,7 +2,7 @@
Capitalizes the first letter of every word in a string. Capitalizes the first letter of every word in a string.
Use `replace()` to match the first character of each word and `toUpperCase()` to capitalize it. Use `String.replace()` to match the first character of each word and `String.toUpperCase()` to capitalize it.
```js ```js
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());

View File

@ -2,8 +2,8 @@
Removes any properties except the ones specified from a JSON object. Removes any properties except the ones specified from a JSON object.
Use `Object.keys()` method to loop over given JSON object and deleting keys that are not `include`d in given array. Use `Object.keys()` method to loop over given JSON object and deleting keys that are not included in given array.
Also if you give it a special key (`childIndicator`) it will search deeply inside it to apply function to inner objects too. If you pass a special key,`childIndicator`, it will search deeply apply the function to inner objects, too.
```js ```js
const cleanObj = (obj, keysToKeep = [], childIndicator) => { const cleanObj = (obj, keysToKeep = [], childIndicator) => {

View File

@ -5,7 +5,7 @@ Counts the occurrences of a value in an array.
Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array. Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array.
```js ```js
const countOccurrences = (arr, value) => arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0); const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a + 0), 0);
``` ```
```js ```js

View File

@ -2,11 +2,11 @@
Converts a number to an array of digits. Converts a number to an array of digits.
Convert the number to a string, using spread operators in ES6(`[...string]`) build an array. Convert the number to a string, using the spread operator (`...`) to build an array.
Use `Array.map()` and `parseInt()` to transform each value to an integer. Use `Array.map()` and `parseInt()` to transform each value to an integer.
```js ```js
const digitize = n => [...('' + n)].map(i => parseInt(i)); const digitize = n => [...`${n}`].map(i => parseInt(i));
``` ```
```js ```js

View File

@ -4,8 +4,10 @@ Computes the new ratings between two or more opponents using the [Elo rating sys
of pre-ratings and returns an array containing post-ratings. of pre-ratings and returns an array containing post-ratings.
The array should be ordered from best performer to worst performer (winner -> loser). The array should be ordered from best performer to worst performer (winner -> loser).
Use the exponent `**` operator and math operators to compute the expected score (chance of winning) Use the exponent `**` operator and math operators to compute the expected score (chance of winning).
of each opponent and compute the new rating for each. Loop through the ratings, using each permutation to compute the post-Elo rating for each player in a pairwise fashion. Omit the second argument to use the default K-factor of 32, or supply a custom K-factor value. For details on the third argument, see the last example. of each opponent and compute the new rating for each.
Loop through the ratings, using each permutation to compute the post-Elo rating for each player in a pairwise fashion.
Omit the second argument to use the default `kFactor` of 32.
```js ```js
const elo = ([...ratings], kFactor = 32, selfRating) => { const elo = ([...ratings], kFactor = 32, selfRating) => {
@ -35,7 +37,7 @@ elo([1200, 1200], 64); // [1232, 1168]
// 4 player FFA, all same rank // 4 player FFA, all same rank
elo([1200, 1200, 1200, 1200]).map(Math.round); // [1246, 1215, 1185, 1154] elo([1200, 1200, 1200, 1200]).map(Math.round); // [1246, 1215, 1185, 1154]
/* /*
For teams, each rating can adjusted based on own team's average rating vs. For teams, each rating can adjusted based on own team's average rating vs.
average rating of opposing team, with the score being added to their average rating of opposing team, with the score being added to their
own individual rating by supplying it as the third argument. own individual rating by supplying it as the third argument.
*/ */

View File

@ -2,7 +2,7 @@
Escapes a string for use in HTML. Escapes a string for use in HTML.
Use `String.replace()` with a regex that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object). Use `String.replace()` with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).
```js ```js
const escapeHTML = str => const escapeHTML = str =>

View File

@ -2,7 +2,7 @@
Escapes a string to use in a regular expression. Escapes a string to use in a regular expression.
Use `replace()` to escape special characters. Use `String.replace()` to escape special characters.
```js ```js
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

View File

@ -2,8 +2,9 @@
Extends a 3-digit color code to a 6-digit color code. Extends a 3-digit color code to a 6-digit color code.
Use `Array.map()`, `split()` and `Array.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form. Use `Array.map()`, `String.split()` and `Array.join()` to join the mapped array for converting a 3-digit RGB notated hexadecimal color-code to the 6-digit form.
`String.slice()` is used to remove `#` from string start since it's added once. `Array.slice()` is used to remove `#` from string start since it's added once.
```js ```js
const extendHex = shortHex => const extendHex = shortHex =>
'#' + '#' +

View File

@ -2,7 +2,7 @@
Flattens an array. Flattens an array.
Use a new array and concatenate it with the spread input array causing a shallow denesting of any contained arrays. Use a new array, `Array.concat()` and the spread operator (`...`) to cause a shallow denesting of any contained arrays.
```js ```js
const flatten = arr => [].concat(...arr); const flatten = arr => [].concat(...arr);

View File

@ -1,6 +1,6 @@
### flip ### flip
Flip takes a function as an argument, then makes the first argument the last Flip takes a function as an argument, then makes the first argument the last.
Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest. Return a closure that takes variadic inputs, and splices the last argument to make it the first argument before applying the rest.

View File

@ -2,8 +2,8 @@
Converts a string from camelcase. Converts a string from camelcase.
Use `replace()` to remove underscores, hyphens, and spaces and convert words to camelcase. Use `String.replace()` to remove underscores, hyphens, and spaces and convert words to camelcase.
Omit the second argument to use a default separator of `_`. Omit the second argument to use a default `separator` of `_`.
```js ```js
const fromCamelCase = (str, separator = '_') => const fromCamelCase = (str, separator = '_') =>

View File

@ -9,10 +9,11 @@ Otherwise, return the GCD of `y` and the remainder of the division `x/y`.
```js ```js
const gcd = (...arr) => { const gcd = (...arr) => {
const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); const _gcd = (x, y) => (!y ? x : gcd(y, x % y));
return [].concat(...arr).reduce((a, b) => _gcd(a, b)); return [...arr].reduce((a, b) => _gcd(a, b));
}; };
``` ```
```js ```js
gcd(8, 36); // 4 gcd(8, 36); // 4
gcd(...[12, 8, 32]); // 4
``` ```

View File

@ -2,7 +2,7 @@
Returns the native type of a value. Returns the native type of a value.
Returns lowercased constructor name of value, "undefined" or "null" if value is undefined or null Returns lowercased constructor name of value, `"undefined"` or `"null"` if value is `undefined` or `null`.
```js ```js
const getType = v => const getType = v =>

View File

@ -2,7 +2,7 @@
Returns an object containing the parameters of the current URL. Returns an object containing the parameters of the current URL.
Use `match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object. Use `String.match()` with an appropriate regular expression to get all key-value pairs, `Array.reduce()` to map and combine them into a single object.
Pass `location.search` as the argument to apply to the current `url`. Pass `location.search` as the argument to apply to the current `url`.
```js ```js

View File

@ -2,7 +2,7 @@
Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with there common difference `step`. Initializes an array containing the numbers in the specified range where `start` and `end` are inclusive with there common difference `step`.
Use `Array(Math.ceil((end+1-start)/step)` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range. Use `Array.from(Math.ceil((end+1-start)/step))` to create an array of the desired length(the amounts of elements is equal to `(end-start)/step` or `(end+1-start)/step` for inclusive end), `Array.map()` to fill with the desired values in a range.
You can omit `start` to use a default value of `0`. You can omit `start` to use a default value of `0`.
You can omit `step` to use a default value of `1`. You can omit `step` to use a default value of `1`.

View File

@ -3,10 +3,10 @@
Initializes and fills an array with the specified values. Initializes and fills an array with the specified values.
Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values. Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values.
You can omit `value` to use a default value of `0`. You can omit `val` to use a default value of `0`.
```js ```js
const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value); const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
``` ```
```js ```js

View File

@ -5,10 +5,9 @@ Checks if the given argument is an array.
Use `Array.isArray()` to check if a value is classified as an array. Use `Array.isArray()` to check if a value is classified as an array.
```js ```js
const isArray = val => !!val && Array.isArray(val); const isArray = val => Array.isArray(val);
``` ```
```js ```js
isArray(null); // false
isArray([1]); // true isArray([1]); // true
``` ```

View File

@ -9,7 +9,6 @@ const isFunction = val => typeof val === 'function';
``` ```
```js ```js
isFunction(null); // false
isFunction('x'); // false isFunction('x'); // false
isFunction(x => x); // true isFunction(x => x); // true
``` ```

View File

@ -1,6 +1,6 @@
### lcm ### lcm
Returns the least common multiple of two or more numbers/arrays. Returns the least common multiple of two or more numbers.
Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple. Use the greatest common divisor (GCD) formula and `Math.abs()` to determine the least common multiple.
The GCD formula uses recursion. The GCD formula uses recursion.
@ -9,11 +9,11 @@ The GCD formula uses recursion.
const lcm = (...arr) => { const lcm = (...arr) => {
const gcd = (x, y) => (!y ? x : gcd(y, x % y)); const gcd = (x, y) => (!y ? x : gcd(y, x % y));
const _lcm = (x, y) => x * y / gcd(x, y); const _lcm = (x, y) => x * y / gcd(x, y);
return [].concat(...arr).reduce((a, b) => _lcm(a, b)); return [...arr].reduce((a, b) => _lcm(a, b));
}; };
``` ```
```js ```js
lcm(12, 7); // 84 lcm(12, 7); // 84
lcm([1, 3, 4], 5); // 60 lcm(...[1, 3, 4, 5]); // 60
``` ```

View File

@ -2,7 +2,7 @@
Replaces all but the last `num` of characters with the specified mask character. Replaces all but the last `num` of characters with the specified mask character.
Use `String.slice()` to grab the portion of the characters that need to be masked and use `String.replace()` with a regex to replace every character with the mask character. Use `String.slice()` to grab the portion of the characters that need to be masked and use `String.replace()` with a regexp to replace every character with the mask character.
Concatenate the masked characters with the remaining unmasked portion of the string. Concatenate the masked characters with the remaining unmasked portion of the string.
Omit the second argument, `num`, to keep a default of `4` characters unmasked. If `num` is negative, the unmasked characters will be at the start of the string. Omit the second argument, `num`, to keep a default of `4` characters unmasked. If `num` is negative, the unmasked characters will be at the start of the string.
Omit the third argument, `mask`, to use a default character of `'*'` for the mask. Omit the third argument, `mask`, to use a default character of `'*'` for the mask.

View File

@ -2,7 +2,7 @@
Negates a predicate function. Negates a predicate function.
Take a predicate function and apply `not` to it with its arguments. Take a predicate function and apply the not operator (`!`) to it with its arguments.
```js ```js
const negate = func => (...args) => !func(...args); const negate = func => (...args) => !func(...args);

View File

@ -2,8 +2,8 @@
Returns a sorted array of objects ordered by properties and orders. Returns a sorted array of objects ordered by properties and orders.
Uses a custom implementation of sort, that reduces the props array argument with a default value of 0, it uses destructuring to swap the properties position depending on the order passed. Uses `Array.sort()`, `Array.reduce()` on the `props` array with a default value of `0`, use array destructuring to swap the properties position depending on the order passed.
If no orders array is passed it sort by 'asc' by default. If no `orders` array is passed it sort by `'asc'` by default.
```js ```js
const orderBy = (arr, props, orders) => const orderBy = (arr, props, orders) =>

View File

@ -2,8 +2,8 @@
Returns `true` if the given string is a palindrome, `false` otherwise. Returns `true` if the given string is a palindrome, `false` otherwise.
Convert string `toLowerCase()` and use `replace()` to remove non-alphanumeric characters from it. Convert string `String.toLowerCase()` and use `String.replace()` to remove non-alphanumeric characters from it.
Then, `split('')` into individual characters, `reverse()`, `join('')` and compare to the original, unreversed string, after converting it `tolowerCase()`. Then, `String.split('')` into individual characters, `Array.reverse()`, `String.join('')` and compare to the original, unreversed string, after converting it `String.tolowerCase()`.
```js ```js
const palindrome = str => { const palindrome = str => {

View File

@ -1,16 +0,0 @@
### repeatString
Repeats a string n times using `String.repeat()`
If no string is provided the default is `""` and the default number of times is 2.
```js
const repeatString = (str = '', num = 2) => {
return num >= 0 ? str.repeat(num) : str;
};
```
```js
repeatString('abc', 3); // 'abcabcabc'
repeatString('abc'); // 'abcabc'
```

View File

@ -2,13 +2,15 @@
Reverses a string. Reverses a string.
Use `split('')` and `Array.reverse()` to reverse the order of the characters in the string. Use the spread operator (`...`) and `Array.reverse()` to reverse the order of the characters in the string.
Combine characters to get a string using `join('')`. Combine characters to get a string using `String.join('')`.
```js ```js
const reverseString = str => const reverseString = str =>
str [..str]
.split('')
.reverse() .reverse()
.join(''); .join('');
``` ```

View File

@ -1,8 +1,8 @@
### sbdm ### sbdm
This algorithm is a simple hash-algorithm that hashes it input string `s` into a whole number. Hashes the input string into a whole number.
Use `split('')` and `Array.reduce()` to create a hash of the input string, utilizing bit shifting. Use `String.split('')` and `Array.reduce()` to create a hash of the input string, utilizing bit shifting.
```js ```js
const sdbm = str => { const sdbm = str => {

View File

@ -1,6 +1,6 @@
### select ### select
Retrieve a property that indicated by the selector from an object. Retrieve a property indicated by the selector from an object.
If the property does not exists returns `undefined`. If the property does not exists returns `undefined`.

View File

@ -2,10 +2,10 @@
Sets the value of a CSS rule for the specified element. Sets the value of a CSS rule for the specified element.
Use `element.style` to set the value of the CSS rule for the specified element to `value`. Use `element.style` to set the value of the CSS rule for the specified element to `val`.
```js ```js
const setStyle = (el, ruleName, value) => (el.style[ruleName] = value); const setStyle = (el, ruleName, val) => (el.style[ruleName] = val);
``` ```
```js ```js

View File

@ -2,7 +2,7 @@
Randomizes the order of the values of an array, returning a new array. Randomizes the order of the values of an array, returning a new array.
Uses the Fisher-Yates algorithm to reorder the elements of the array, based on the [Lodash implementation](https://github.com/lodash/lodash/blob/b2ea6b1cd251796dcb5f9700c4911a7b6223920b/shuffle.js), but as a pure function. Uses the [Fisher-Yates algorithm](https://github.com/chalarangelo/30-seconds-of-code#shuffle) to reorder the elements of the array.
```js ```js
const shuffle = ([...arr]) => { const shuffle = ([...arr]) => {

View File

@ -2,7 +2,7 @@
Returns an array of elements that appear in both arrays. Returns an array of elements that appear in both arrays.
Use `filter()` to remove values that are not part of `values`, determined using `includes()`. Use `Array.filter()` to remove values that are not part of `values`, determined using `Array.includes()`.
```js ```js
const similarity = (arr, values) => arr.filter(v => values.includes(v)); const similarity = (arr, values) => arr.filter(v => values.includes(v));

View File

@ -2,20 +2,20 @@
Get size of arrays, objects or strings. Get size of arrays, objects or strings.
Get type of `value` (`array`, `object` or `string`). Get type of `val` (`array`, `object` or `string`).
Use `length` property for arrays. Use `length` property for arrays.
Use `length` or `size` value if available or number of keys for objects. Use `length` or `size` value if available or number of keys for objects.
Use `size` of a [`Blob` object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) created from `value` for strings. Use `size` of a [`Blob` object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) created from `val` for strings.
Split strings into array of characters with `split('')` and return its length. Split strings into array of characters with `split('')` and return its length.
```js ```js
const size = value => const size = val =>
Array.isArray(value) Array.isArray(val)
? value.length ? val.length
: value && typeof value === 'object' : val && typeof val === 'object'
? value.size || value.length || Object.keys(value).length ? val.size || val.length || Object.keys(val).length
: typeof value === 'string' ? new Blob([value]).size : 0; : typeof val === 'string' ? new Blob([val]).size : 0;
``` ```
```js ```js

View File

@ -2,14 +2,10 @@
Alphabetically sorts the characters in a string. Alphabetically sorts the characters in a string.
Split the string using `split('')`, `Array.sort()` utilizing `localeCompare()`, recombine using `join('')`. Use the spread operator (`...`), `Array.sort()` and `String.localeCompare()` to sort the characters in `str`, recombine using `String.join('')`.
```js ```js
const sortCharactersInString = str => const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
str
.split('')
.sort((a, b) => a.localeCompare(b))
.join('');
``` ```
```js ```js

View File

@ -5,9 +5,9 @@ Returns the sum of two or more numbers/arrays.
Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`. Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`.
```js ```js
const sum = (...arr) => [].concat(...arr).reduce((acc, val) => acc + val, 0); const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
``` ```
```js ```js
sum([1, 2, 3, 4]); // 10 sum(...[1, 2, 3, 4]); // 10
``` ```

View File

@ -2,7 +2,7 @@
Returns all elements in an array except for the first one. Returns all elements in an array except for the first one.
Return `arr.slice(1)` if the array's `length` is more than `1`, otherwise, return the whole array. Return `Array.slice(1)` if the array's `length` is more than `1`, otherwise, return the whole array.
```js ```js
const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); const tail = arr => (arr.length > 1 ? arr.slice(1) : arr);

View File

@ -2,8 +2,7 @@
Converts a string to camelcase. Converts a string to camelcase.
Break the string into words and combine them capitalizing the first letter of each word. Break the string into words and combine them capitalizing the first letter of each word, using a regexp.
For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1).
```js ```js
const toCamelCase = str => { const toCamelCase = str => {

View File

@ -2,8 +2,7 @@
Converts a string to kebab case. Converts a string to kebab case.
Break the string into words and combine them using `-` as a separator. Break the string into words and combine them adding `-` as a separator, using a regexp.
For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1).
```js ```js
const toKebabCase = str => const toKebabCase = str =>

View File

@ -2,8 +2,7 @@
Converts a string to snake case. Converts a string to snake case.
Break the string into words and combine them using `_` as a separator. Break the string into words and combine them adding `_` as a separator, using a regexp.
For more detailed explanation of this Regex, [visit this Site](https://regex101.com/r/bMCgAB/1).
```js ```js
const toSnakeCase = str => const toSnakeCase = str =>

View File

@ -1,7 +1,7 @@
### tomorrow ### tomorrow
Results in a string representation of tomorrow's date. Results in a string representation of tomorrow's date.
Use `new Date()` to get today's date, adding `86400000` of seconds to it(24 hours), using `toISOString` to convert Date object to string. Use `new Date()` to get today's date, adding `86400000` of seconds to it(24 hours), using `Date.toISOString()` to convert Date object to string.
```js ```js
const tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0]; const tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0];

View File

@ -3,7 +3,7 @@
Truncates a string up to a specified length. Truncates a string up to a specified length.
Determine if the string's `length` is greater than `num`. Determine if the string's `length` is greater than `num`.
Return the string truncated to the desired length, with `...` appended to the end or the original string. Return the string truncated to the desired length, with `'...'` appended to the end or the original string.
```js ```js
const truncateString = (str, num) => const truncateString = (str, num) =>

View File

@ -2,7 +2,7 @@
Returns `true` if the given value is a number, `false` otherwise. Returns `true` if the given value is a number, `false` otherwise.
Use `!isNaN` in combination with `parseFloat()` to check if the argument is a number. Use `!isNaN()` in combination with `parseFloat()` to check if the argument is a number.
Use `isFinite()` to check if the number is finite. Use `isFinite()` to check if the number is finite.
Use `Number()` to check if the coercion holds. Use `Number()` to check if the coercion holds.

View File

@ -2,8 +2,8 @@
Converts a given string into an array of words. Converts a given string into an array of words.
Use `String.split()` with a supplied pattern (defaults to non-alpha as a regex) to convert to an array of strings. Use `Array.filter()` to remove any empty strings. Use `String.split()` with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. Use `Array.filter()` to remove any empty strings.
Omit the second argument to use the default regex. Omit the second argument to use the default regexp.
```js ```js
const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);

View File

@ -18,7 +18,7 @@
⚠️ **WARNING:** Snippets are not production ready. ⚠️ **WARNING:** Snippets are not production ready.
You can find a package with all the snippets on [npm](https://www.npmjs.com/package/30-seconds-of-code). You can find a package with all the snippets on [npm](https://www.npmjs.com/package/30-seconds-of-code).
``` ```
npm install 30-seconds-of-code npm install 30-seconds-of-code

View File

@ -14,13 +14,17 @@
<link rel="icon" type="image/png" href="favicon.png"> <link rel="icon" type="image/png" href="favicon.png">
<script> <script>
const search = (node) => { const search = (node) => {
let matchingTags = [];
Array.from(node.parentElement.parentElement.getElementsByTagName('a')).forEach(x => { Array.from(node.parentElement.parentElement.getElementsByTagName('a')).forEach(x => {
x.style.display = x.getAttribute("href").toUpperCase().indexOf(node.value.toUpperCase()) + 1 ? '' : 'none' let data = [x.innerText.toLowerCase(), ...x.getAttribute('tags').split(',')].map(v => !!(v.indexOf(node.value.toLowerCase()) + 1));
if(data.includes(true)){
x.style.display = '';
matchingTags.push(x.getAttribute('tags').split(',')[0]);
}
else x.style.display = 'none';
}); });
Array.from( node.parentElement.parentElement.children ) Array.from(node.parentElement.parentElement.getElementsByTagName('h3')).forEach(x => {
.filter( x => !( x.tagName == 'A' && x.style.display == 'none' ) ) x.style.display = matchingTags.includes(x.innerText.toLowerCase()) ? '' : 'none';
.forEach( ( element, index, source) => {
element.style.display = (element.tagName == 'H3' && index + 1 == source.length ? 'none' : element.tagName == 'H3' && source[index + 1].tagName == 'H3' ? 'none' : '')
}) })
} }
function loader() { function loader() {