Travis build: 1242 [cron]
This commit is contained in:
50
dist/_30s.es5.js
vendored
50
dist/_30s.es5.js
vendored
@ -408,6 +408,21 @@ var elo = function elo(_ref) {
|
||||
return ratings;
|
||||
};
|
||||
|
||||
var _typeof = 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 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 === 'undefined' ? 'undefined' : _typeof(a)) != 'object' && (typeof b === 'undefined' ? 'undefined' : _typeof(b)) !== 'object') return a === b;
|
||||
if (a === null || a === undefined || b === null || b === undefined) return false;
|
||||
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 {
|
||||
@ -760,16 +775,16 @@ var isPrime = function isPrime(num) {
|
||||
}return num >= 2;
|
||||
};
|
||||
|
||||
var _typeof = 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 isPrimitive = function isPrimitive(val) {
|
||||
return !['object', 'function'].includes(typeof val === 'undefined' ? 'undefined' : _typeof(val)) || val === null;
|
||||
};
|
||||
|
||||
var _typeof$1 = 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 isPrimitive = function isPrimitive(val) {
|
||||
return !['object', 'function'].includes(typeof val === 'undefined' ? 'undefined' : _typeof$1(val)) || val === null;
|
||||
};
|
||||
|
||||
var _typeof$2 = 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 isPromiseLike = function isPromiseLike(obj) {
|
||||
return obj !== null && ((typeof obj === 'undefined' ? 'undefined' : _typeof$1(obj)) === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
|
||||
return obj !== null && ((typeof obj === 'undefined' ? 'undefined' : _typeof$2(obj)) === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
|
||||
};
|
||||
|
||||
var _slicedToArray$1 = 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"); } }; }();
|
||||
@ -811,10 +826,10 @@ var isString = function isString(val) {
|
||||
return typeof val === 'string';
|
||||
};
|
||||
|
||||
var _typeof$2 = 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$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 isSymbol = function isSymbol(val) {
|
||||
return (typeof val === 'undefined' ? 'undefined' : _typeof$2(val)) === 'symbol';
|
||||
return (typeof val === 'undefined' ? 'undefined' : _typeof$3(val)) === 'symbol';
|
||||
};
|
||||
|
||||
var isTravisCI = function isTravisCI() {
|
||||
@ -1116,7 +1131,7 @@ var pipeFunctions = function pipeFunctions() {
|
||||
});
|
||||
};
|
||||
|
||||
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 pluralize = function pluralize(val, word) {
|
||||
var plural = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : word + 's';
|
||||
@ -1125,7 +1140,7 @@ var pluralize = function pluralize(val, 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) {
|
||||
if ((typeof val === 'undefined' ? 'undefined' : _typeof$4(val)) === 'object') return function (num, word) {
|
||||
return _pluralize(num, word, val[word]);
|
||||
};
|
||||
return _pluralize(val, word, plural);
|
||||
@ -1229,6 +1244,13 @@ var randomHexColorCode = function randomHexColorCode() {
|
||||
return '#' + (n.length !== 6 ? (Math.random() * 0xf | 0).toString(16) + n : n);
|
||||
};
|
||||
|
||||
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;
|
||||
};
|
||||
@ -1390,10 +1412,10 @@ var similarity = function similarity(arr, values) {
|
||||
});
|
||||
};
|
||||
|
||||
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 _typeof$5 = 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(val) {
|
||||
return Array.isArray(val) ? val.length : val && (typeof val === 'undefined' ? 'undefined' : _typeof$4(val)) === 'object' ? val.size || val.length || Object.keys(val).length : typeof val === 'string' ? new Blob([val]).size : 0;
|
||||
return Array.isArray(val) ? val.length : val && (typeof val === 'undefined' ? 'undefined' : _typeof$5(val)) === 'object' ? val.size || val.length || Object.keys(val).length : typeof val === 'string' ? new Blob([val]).size : 0;
|
||||
};
|
||||
|
||||
var sleep = function sleep(ms) {
|
||||
@ -1634,7 +1656,7 @@ var zipObject = function zipObject(props, values) {
|
||||
}, {});
|
||||
};
|
||||
|
||||
var imports = { JSONToFile: JSONToFile, RGBToHex: RGBToHex, UUIDGeneratorBrowser: UUIDGeneratorBrowser, UUIDGeneratorNode: UUIDGeneratorNode, anagrams: anagrams, arrayToHtmlList: arrayToHtmlList, average: average, averageBy: averageBy, bottomVisible: bottomVisible, byteSize: byteSize, call: call, capitalize: capitalize, capitalizeEveryWord: capitalizeEveryWord, chainAsync: chainAsync, chunk: chunk, clampNumber: clampNumber, cleanObj: cleanObj, cloneRegExp: cloneRegExp, coalesce: coalesce, coalesceFactory: coalesceFactory, collectInto: collectInto, colorize: colorize, compact: compact, compose: compose, copyToClipboard: copyToClipboard, countBy: countBy, countOccurrences: countOccurrences, createElement: createElement, createEventHub: createEventHub, currentURL: currentURL, curry: curry, decapitalize: decapitalize, deepFlatten: deepFlatten, defer: defer, detectDeviceType: detectDeviceType, difference: difference, differenceWith: differenceWith, digitize: digitize, distance: distance, distinctValuesOfArray: distinctValuesOfArray, dropElements: dropElements, dropRight: dropRight, elementIsVisibleInViewport: elementIsVisibleInViewport, elo: elo, escapeHTML: escapeHTML, escapeRegExp: escapeRegExp, everyNth: everyNth, extendHex: extendHex, factorial: factorial, fibonacci: fibonacci, filterNonUnique: filterNonUnique, findLast: findLast, flatten: flatten, flip: flip, forEachRight: forEachRight, formatDuration: formatDuration, fromCamelCase: fromCamelCase, functionName: functionName, functions: functions, 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, httpGet: httpGet, httpPost: httpPost, httpsRedirect: httpsRedirect, inRange: inRange, indexOfAll: indexOfAll, initial: initial, initialize2DArray: initialize2DArray, initializeArrayWithRange: initializeArrayWithRange, initializeArrayWithValues: initializeArrayWithValues, intersection: intersection, invertKeyValues: invertKeyValues, isAbsoluteURL: isAbsoluteURL, isArray: isArray, isArrayLike: isArrayLike, isBoolean: isBoolean, isDivisible: isDivisible, isEven: isEven, isFunction: isFunction, isLowerCase: isLowerCase, isNull: isNull, isNumber: isNumber, isObject: isObject, isPrime: isPrime, isPrimitive: isPrimitive, isPromiseLike: isPromiseLike, isSorted: isSorted, isString: isString, isSymbol: isSymbol, isTravisCI: isTravisCI, isUpperCase: isUpperCase, isValidJSON: isValidJSON, join: join, last: last, lcm: lcm, longestItem: longestItem, lowercaseKeys: lowercaseKeys, luhnCheck: luhnCheck, mapKeys: mapKeys, mapObject: mapObject, mapValues: mapValues, mask: mask, maxBy: maxBy, maxN: maxN, median: median, memoize: memoize, merge: merge, minBy: minBy, minN: minN, negate: negate, nthElement: nthElement, objectFromPairs: objectFromPairs, objectToPairs: objectToPairs, off: off, on: on, onUserInputChange: onUserInputChange, once: once, orderBy: orderBy, palindrome: palindrome, parseCookie: parseCookie, partition: partition, percentile: percentile, pick: pick, pipeFunctions: pipeFunctions, pluralize: pluralize, powerset: powerset, prettyBytes: prettyBytes, primes: primes, promisify: promisify, pull: pull, pullAtIndex: pullAtIndex, pullAtValue: pullAtValue, randomHexColorCode: randomHexColorCode, randomIntegerInRange: randomIntegerInRange, randomNumberInRange: randomNumberInRange, readFileLines: readFileLines, redirect: redirect, reducedFilter: reducedFilter, remove: remove, reverseString: reverseString, round: round, runAsync: runAsync, runPromisesInSeries: runPromisesInSeries, sample: sample, sampleSize: sampleSize, scrollToTop: scrollToTop, sdbm: sdbm, select: select, serializeCookie: serializeCookie, setStyle: setStyle, shallowClone: shallowClone, show: show, shuffle: shuffle, similarity: similarity, size: size, sleep: sleep, sortCharactersInString: sortCharactersInString, sortedIndex: sortedIndex, splitLines: splitLines, spreadOver: spreadOver, standardDeviation: standardDeviation, sum: sum, sumBy: sumBy, sumPower: sumPower, symmetricDifference: symmetricDifference, tail: tail, take: take, takeRight: takeRight, timeTaken: timeTaken, toCamelCase: toCamelCase, toDecimalMark: toDecimalMark, toKebabCase: toKebabCase, toOrdinalSuffix: toOrdinalSuffix, toSafeInteger: toSafeInteger, toSnakeCase: toSnakeCase, toggleClass: toggleClass, tomorrow: tomorrow, transform: transform, truncateString: truncateString, truthCheckCollection: truthCheckCollection, unescapeHTML: unescapeHTML, union: union, untildify: untildify, validateNumber: validateNumber, without: without, words: words, yesNo: yesNo, zip: zip, zipObject: zipObject };
|
||||
var imports = { JSONToFile: JSONToFile, RGBToHex: RGBToHex, UUIDGeneratorBrowser: UUIDGeneratorBrowser, UUIDGeneratorNode: UUIDGeneratorNode, anagrams: anagrams, arrayToHtmlList: arrayToHtmlList, average: average, averageBy: averageBy, bottomVisible: bottomVisible, byteSize: byteSize, call: call, capitalize: capitalize, capitalizeEveryWord: capitalizeEveryWord, chainAsync: chainAsync, chunk: chunk, clampNumber: clampNumber, cleanObj: cleanObj, cloneRegExp: cloneRegExp, coalesce: coalesce, coalesceFactory: coalesceFactory, collectInto: collectInto, colorize: colorize, compact: compact, compose: compose, copyToClipboard: copyToClipboard, countBy: countBy, countOccurrences: countOccurrences, createElement: createElement, createEventHub: createEventHub, currentURL: currentURL, curry: curry, decapitalize: decapitalize, deepFlatten: deepFlatten, defer: defer, detectDeviceType: detectDeviceType, difference: difference, differenceWith: differenceWith, digitize: digitize, distance: distance, distinctValuesOfArray: distinctValuesOfArray, dropElements: dropElements, dropRight: dropRight, elementIsVisibleInViewport: elementIsVisibleInViewport, elo: elo, equals: equals, escapeHTML: escapeHTML, escapeRegExp: escapeRegExp, everyNth: everyNth, extendHex: extendHex, factorial: factorial, fibonacci: fibonacci, filterNonUnique: filterNonUnique, findLast: findLast, flatten: flatten, flip: flip, forEachRight: forEachRight, formatDuration: formatDuration, fromCamelCase: fromCamelCase, functionName: functionName, functions: functions, 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, httpGet: httpGet, httpPost: httpPost, httpsRedirect: httpsRedirect, inRange: inRange, indexOfAll: indexOfAll, initial: initial, initialize2DArray: initialize2DArray, initializeArrayWithRange: initializeArrayWithRange, initializeArrayWithValues: initializeArrayWithValues, intersection: intersection, invertKeyValues: invertKeyValues, isAbsoluteURL: isAbsoluteURL, isArray: isArray, isArrayLike: isArrayLike, isBoolean: isBoolean, isDivisible: isDivisible, isEven: isEven, isFunction: isFunction, isLowerCase: isLowerCase, isNull: isNull, isNumber: isNumber, isObject: isObject, isPrime: isPrime, isPrimitive: isPrimitive, isPromiseLike: isPromiseLike, isSorted: isSorted, isString: isString, isSymbol: isSymbol, isTravisCI: isTravisCI, isUpperCase: isUpperCase, isValidJSON: isValidJSON, join: join, last: last, lcm: lcm, longestItem: longestItem, lowercaseKeys: lowercaseKeys, luhnCheck: luhnCheck, mapKeys: mapKeys, mapObject: mapObject, mapValues: mapValues, mask: mask, maxBy: maxBy, maxN: maxN, median: median, memoize: memoize, merge: merge, minBy: minBy, minN: minN, negate: negate, nthElement: nthElement, objectFromPairs: objectFromPairs, objectToPairs: objectToPairs, off: off, on: on, onUserInputChange: onUserInputChange, once: once, orderBy: orderBy, palindrome: palindrome, parseCookie: parseCookie, partition: partition, percentile: percentile, pick: pick, pipeFunctions: pipeFunctions, pluralize: pluralize, powerset: powerset, prettyBytes: prettyBytes, primes: primes, promisify: promisify, pull: pull, pullAtIndex: pullAtIndex, pullAtValue: pullAtValue, randomHexColorCode: randomHexColorCode, randomIntArrayInRange: randomIntArrayInRange, randomIntegerInRange: randomIntegerInRange, randomNumberInRange: randomNumberInRange, readFileLines: readFileLines, redirect: redirect, reducedFilter: reducedFilter, remove: remove, reverseString: reverseString, round: round, runAsync: runAsync, runPromisesInSeries: runPromisesInSeries, sample: sample, sampleSize: sampleSize, scrollToTop: scrollToTop, sdbm: sdbm, select: select, serializeCookie: serializeCookie, setStyle: setStyle, shallowClone: shallowClone, show: show, shuffle: shuffle, similarity: similarity, size: size, sleep: sleep, sortCharactersInString: sortCharactersInString, sortedIndex: sortedIndex, splitLines: splitLines, spreadOver: spreadOver, standardDeviation: standardDeviation, sum: sum, sumBy: sumBy, sumPower: sumPower, symmetricDifference: symmetricDifference, tail: tail, take: take, takeRight: takeRight, timeTaken: timeTaken, toCamelCase: toCamelCase, toDecimalMark: toDecimalMark, toKebabCase: toKebabCase, toOrdinalSuffix: toOrdinalSuffix, toSafeInteger: toSafeInteger, toSnakeCase: toSnakeCase, toggleClass: toggleClass, tomorrow: tomorrow, transform: transform, truncateString: truncateString, truthCheckCollection: truthCheckCollection, unescapeHTML: unescapeHTML, union: union, untildify: untildify, validateNumber: validateNumber, without: without, words: words, yesNo: yesNo, zip: zip, zipObject: zipObject };
|
||||
|
||||
return imports;
|
||||
|
||||
|
||||
2
dist/_30s.es5.min.js
vendored
2
dist/_30s.es5.min.js
vendored
File diff suppressed because one or more lines are too long
16
dist/_30s.esm.js
vendored
16
dist/_30s.esm.js
vendored
@ -215,6 +215,17 @@ const elo = ([...ratings], kFactor = 32, selfRating) => {
|
||||
return ratings;
|
||||
};
|
||||
|
||||
const equals = (a, b) => {
|
||||
if (a === b) return true;
|
||||
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
|
||||
if (!a || !b || (typeof a != 'object' && typeof b !== 'object')) return a === b;
|
||||
if (a === null || a === undefined || b === null || b === undefined) return false;
|
||||
if (a.prototype !== b.prototype) return false;
|
||||
let keys = Object.keys(a);
|
||||
if (keys.length !== Object.keys(b).length) return false;
|
||||
return keys.every(k => equals(a[k], b[k]));
|
||||
};
|
||||
|
||||
const escapeHTML = str =>
|
||||
str.replace(
|
||||
/[&<>'"]/g,
|
||||
@ -719,6 +730,9 @@ const randomHexColorCode = () => {
|
||||
return '#' + (n.length !== 6 ? ((Math.random() * 0xf) | 0).toString(16) + n : n);
|
||||
};
|
||||
|
||||
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;
|
||||
@ -968,6 +982,6 @@ const zip = (...arrays) => {
|
||||
const zipObject = (props, values) =>
|
||||
props.reduce((obj, prop, index) => (obj[prop] = values[index], obj), {});
|
||||
|
||||
var imports = {JSONToFile,RGBToHex,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,average,averageBy,bottomVisible,byteSize,call,capitalize,capitalizeEveryWord,chainAsync,chunk,clampNumber,cleanObj,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,copyToClipboard,countBy,countOccurrences,createElement,createEventHub,currentURL,curry,decapitalize,deepFlatten,defer,detectDeviceType,difference,differenceWith,digitize,distance,distinctValuesOfArray,dropElements,dropRight,elementIsVisibleInViewport,elo,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,findLast,flatten,flip,forEachRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,getDaysDiffBetweenDates,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,inRange,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithValues,intersection,invertKeyValues,isAbsoluteURL,isArray,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isLowerCase,isNull,isNumber,isObject,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isUpperCase,isValidJSON,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapValues,mask,maxBy,maxN,median,memoize,merge,minBy,minN,negate,nthElement,objectFromPairs,objectToPairs,off,on,onUserInputChange,once,orderBy,palindrome,parseCookie,partition,percentile,pick,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,randomHexColorCode,randomIntegerInRange,randomNumberInRange,readFileLines,redirect,reducedFilter,remove,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,select,serializeCookie,setStyle,shallowClone,show,shuffle,similarity,size,sleep,sortCharactersInString,sortedIndex,splitLines,spreadOver,standardDeviation,sum,sumBy,sumPower,symmetricDifference,tail,take,takeRight,timeTaken,toCamelCase,toDecimalMark,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toggleClass,tomorrow,transform,truncateString,truthCheckCollection,unescapeHTML,union,untildify,validateNumber,without,words,yesNo,zip,zipObject,}
|
||||
var imports = {JSONToFile,RGBToHex,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,average,averageBy,bottomVisible,byteSize,call,capitalize,capitalizeEveryWord,chainAsync,chunk,clampNumber,cleanObj,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,copyToClipboard,countBy,countOccurrences,createElement,createEventHub,currentURL,curry,decapitalize,deepFlatten,defer,detectDeviceType,difference,differenceWith,digitize,distance,distinctValuesOfArray,dropElements,dropRight,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,findLast,flatten,flip,forEachRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,getDaysDiffBetweenDates,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,inRange,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithValues,intersection,invertKeyValues,isAbsoluteURL,isArray,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isLowerCase,isNull,isNumber,isObject,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isUpperCase,isValidJSON,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapValues,mask,maxBy,maxN,median,memoize,merge,minBy,minN,negate,nthElement,objectFromPairs,objectToPairs,off,on,onUserInputChange,once,orderBy,palindrome,parseCookie,partition,percentile,pick,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,redirect,reducedFilter,remove,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,select,serializeCookie,setStyle,shallowClone,show,shuffle,similarity,size,sleep,sortCharactersInString,sortedIndex,splitLines,spreadOver,standardDeviation,sum,sumBy,sumPower,symmetricDifference,tail,take,takeRight,timeTaken,toCamelCase,toDecimalMark,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toggleClass,tomorrow,transform,truncateString,truthCheckCollection,unescapeHTML,union,untildify,validateNumber,without,words,yesNo,zip,zipObject,}
|
||||
|
||||
export default imports;
|
||||
|
||||
16
dist/_30s.js
vendored
16
dist/_30s.js
vendored
@ -221,6 +221,17 @@ const elo = ([...ratings], kFactor = 32, selfRating) => {
|
||||
return ratings;
|
||||
};
|
||||
|
||||
const equals = (a, b) => {
|
||||
if (a === b) return true;
|
||||
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
|
||||
if (!a || !b || (typeof a != 'object' && typeof b !== 'object')) return a === b;
|
||||
if (a === null || a === undefined || b === null || b === undefined) return false;
|
||||
if (a.prototype !== b.prototype) return false;
|
||||
let keys = Object.keys(a);
|
||||
if (keys.length !== Object.keys(b).length) return false;
|
||||
return keys.every(k => equals(a[k], b[k]));
|
||||
};
|
||||
|
||||
const escapeHTML = str =>
|
||||
str.replace(
|
||||
/[&<>'"]/g,
|
||||
@ -725,6 +736,9 @@ const randomHexColorCode = () => {
|
||||
return '#' + (n.length !== 6 ? ((Math.random() * 0xf) | 0).toString(16) + n : n);
|
||||
};
|
||||
|
||||
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;
|
||||
@ -974,7 +988,7 @@ const zip = (...arrays) => {
|
||||
const zipObject = (props, values) =>
|
||||
props.reduce((obj, prop, index) => (obj[prop] = values[index], obj), {});
|
||||
|
||||
var imports = {JSONToFile,RGBToHex,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,average,averageBy,bottomVisible,byteSize,call,capitalize,capitalizeEveryWord,chainAsync,chunk,clampNumber,cleanObj,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,copyToClipboard,countBy,countOccurrences,createElement,createEventHub,currentURL,curry,decapitalize,deepFlatten,defer,detectDeviceType,difference,differenceWith,digitize,distance,distinctValuesOfArray,dropElements,dropRight,elementIsVisibleInViewport,elo,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,findLast,flatten,flip,forEachRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,getDaysDiffBetweenDates,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,inRange,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithValues,intersection,invertKeyValues,isAbsoluteURL,isArray,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isLowerCase,isNull,isNumber,isObject,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isUpperCase,isValidJSON,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapValues,mask,maxBy,maxN,median,memoize,merge,minBy,minN,negate,nthElement,objectFromPairs,objectToPairs,off,on,onUserInputChange,once,orderBy,palindrome,parseCookie,partition,percentile,pick,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,randomHexColorCode,randomIntegerInRange,randomNumberInRange,readFileLines,redirect,reducedFilter,remove,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,select,serializeCookie,setStyle,shallowClone,show,shuffle,similarity,size,sleep,sortCharactersInString,sortedIndex,splitLines,spreadOver,standardDeviation,sum,sumBy,sumPower,symmetricDifference,tail,take,takeRight,timeTaken,toCamelCase,toDecimalMark,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toggleClass,tomorrow,transform,truncateString,truthCheckCollection,unescapeHTML,union,untildify,validateNumber,without,words,yesNo,zip,zipObject,}
|
||||
var imports = {JSONToFile,RGBToHex,UUIDGeneratorBrowser,UUIDGeneratorNode,anagrams,arrayToHtmlList,average,averageBy,bottomVisible,byteSize,call,capitalize,capitalizeEveryWord,chainAsync,chunk,clampNumber,cleanObj,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compose,copyToClipboard,countBy,countOccurrences,createElement,createEventHub,currentURL,curry,decapitalize,deepFlatten,defer,detectDeviceType,difference,differenceWith,digitize,distance,distinctValuesOfArray,dropElements,dropRight,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterNonUnique,findLast,flatten,flip,forEachRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,getDaysDiffBetweenDates,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,inRange,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithValues,intersection,invertKeyValues,isAbsoluteURL,isArray,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isLowerCase,isNull,isNumber,isObject,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isUpperCase,isValidJSON,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapValues,mask,maxBy,maxN,median,memoize,merge,minBy,minN,negate,nthElement,objectFromPairs,objectToPairs,off,on,onUserInputChange,once,orderBy,palindrome,parseCookie,partition,percentile,pick,pipeFunctions,pluralize,powerset,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,redirect,reducedFilter,remove,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,select,serializeCookie,setStyle,shallowClone,show,shuffle,similarity,size,sleep,sortCharactersInString,sortedIndex,splitLines,spreadOver,standardDeviation,sum,sumBy,sumPower,symmetricDifference,tail,take,takeRight,timeTaken,toCamelCase,toDecimalMark,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toggleClass,tomorrow,transform,truncateString,truthCheckCollection,unescapeHTML,union,untildify,validateNumber,without,words,yesNo,zip,zipObject,}
|
||||
|
||||
return imports;
|
||||
|
||||
|
||||
2
dist/_30s.min.js
vendored
2
dist/_30s.min.js
vendored
File diff suppressed because one or more lines are too long
@ -6,6 +6,269 @@ These snippets, while useful and interesting, didn't quite make it into the repo
|
||||
|
||||
## Table of Contents
|
||||
|
||||
* [`JSONToDate.md`](#jsontodate.md)
|
||||
* [`speechSynthesis.md`](#speechsynthesis.md)
|
||||
* [`binarySearch.md`](#binarysearch.md)
|
||||
* [`collatz.md`](#collatz.md)
|
||||
* [`countVowels.md`](#countvowels.md)
|
||||
* [`factors.md`](#factors.md)
|
||||
* [`fibonacciCountUntilNum.md`](#fibonaccicountuntilnum.md)
|
||||
* [`fibonacciUntilNum.md`](#fibonacciuntilnum.md)
|
||||
* [`README.md`](#readme.md)
|
||||
* [`httpDelete.md`](#httpdelete.md)
|
||||
* [`httpPut.md`](#httpput.md)
|
||||
* [`isArmstrongNumber.md`](#isarmstrongnumber.md)
|
||||
* [`quickSort.md`](#quicksort.md)
|
||||
* [`removeVowels.md`](#removevowels.md)
|
||||
* [`solveRPN.md`](#solverpn.md)
|
||||
* [`howManyTimes.md`](#howmanytimes.md)
|
||||
|
||||
---
|
||||
|
||||
### JSONToDate
|
||||
|
||||
Converts a JSON object to a date.
|
||||
|
||||
Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`).
|
||||
|
||||
```js
|
||||
const JSONToDate = arr => {
|
||||
const dt = new Date(parseInt(arr.toString().substr(6)));
|
||||
return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
JSONToDate(/Date(1489525200000)/); // "14/3/2017"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### speechSynthesis
|
||||
|
||||
Performs speech synthesis (experimental).
|
||||
|
||||
Use `SpeechSynthesisUtterance.voice` and `window.speechSynthesis.getVoices()` to convert a message to speech.
|
||||
Use `window.speechSynthesis.speak()` to play the message.
|
||||
|
||||
Learn more about the [SpeechSynthesisUtterance interface of the Web Speech API](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance).
|
||||
|
||||
```js
|
||||
const speechSynthesis = message => {
|
||||
const msg = new SpeechSynthesisUtterance(message);
|
||||
msg.voice = window.speechSynthesis.getVoices()[0];
|
||||
window.speechSynthesis.speak(msg);
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
speechSynthesis('Hello, World'); // // plays the message
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### binarySearch
|
||||
|
||||
Use recursion. Similar to `Array.indexOf()` that finds the index of a value within an array.
|
||||
The 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.indexOf()`.
|
||||
|
||||
Search a sorted array by repeatedly dividing the search interval in half.
|
||||
Begin with an interval covering the whole array.
|
||||
If 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.
|
||||
Repeatedly 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`.
|
||||
|
||||
```js
|
||||
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;
|
||||
}
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2
|
||||
binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### collatz
|
||||
|
||||
Applies the Collatz algorithm.
|
||||
|
||||
If `n` is even, return `n/2`. Otherwise, return `3n+1`.
|
||||
|
||||
```js
|
||||
const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1);
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
collatz(8); // 4
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### countVowels
|
||||
|
||||
Retuns `number` of vowels in provided string.
|
||||
|
||||
Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`.
|
||||
|
||||
```js
|
||||
const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
countVowels('foobar'); // 3
|
||||
countVowels('gym'); // 0
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### factors
|
||||
|
||||
Returns the array of factors of the given `num`.
|
||||
If the second argument is set to `true` returns only the prime factors of `num`.
|
||||
If `num` is `1` or `0` returns an empty array.
|
||||
If `num` is less than `0` returns all the factors of `-int` together with their additive inverses.
|
||||
|
||||
Use `Array.from()`, `Array.map()` and `Array.filter()` to find all the factors of `num`.
|
||||
If given `num` is negative, use `Array.reduce()` to add the additive inverses to the array.
|
||||
Return all results if `primes` is `false`, else determine and return only the prime factors using `isPrime` and `Array.filter()`.
|
||||
Omit the second argument, `primes`, to return prime and non-prime factors by default.
|
||||
|
||||
**Note**:- _Negative numbers are not considered prime._
|
||||
|
||||
```js
|
||||
const factors = (num, primes = false) => {
|
||||
const isPrime = num => {
|
||||
const boundary = Math.floor(Math.sqrt(num));
|
||||
for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
|
||||
return num >= 2;
|
||||
};
|
||||
const isNeg = num < 0;
|
||||
num = isNeg ? -num : num;
|
||||
let array = Array.from({ length: num - 1 })
|
||||
.map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))
|
||||
.filter(val => val);
|
||||
if (isNeg)
|
||||
array = array.reduce((acc, val) => {
|
||||
acc.push(val);
|
||||
acc.push(-val);
|
||||
return acc;
|
||||
}, []);
|
||||
return primes ? array.filter(isPrime) : array;
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
factors(12); // [2,3,4,6,12]
|
||||
factors(12, true); // [2,3]
|
||||
factors(-12); // [2, -2, 3, -3, 4, -4, 6, -6, 12, -12]
|
||||
factors(-12, true); // [2,3]
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### fibonacciCountUntilNum
|
||||
|
||||
Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive).
|
||||
|
||||
Use a mathematical formula to calculate the number of fibonacci numbers until `num`.
|
||||
|
||||
```js
|
||||
const fibonacciCountUntilNum = num =>
|
||||
Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
fibonacciCountUntilNum(10); // 7
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### fibonacciUntilNum
|
||||
|
||||
Generates an array, containing the Fibonacci sequence, up until the nth term.
|
||||
|
||||
Create an empty array of the specific length, initializing the first two values (`0` and `1`).
|
||||
Use `Array.reduce()` to add values into the array, using the sum of the last two values, except for the first two.
|
||||
Uses a mathematical formula to calculate the length of the array required.
|
||||
|
||||
```js
|
||||
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),
|
||||
[]
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||

|
||||
|
||||
# Snippets Archive
|
||||
|
||||
These snippets, while useful and interesting, didn't quite make it into the repository due to either having very specific use-cases or being outdated. However we felt like they might still be useful to some readers, so here they are.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
* [`JSONToDate.md`](#jsontodate.md)
|
||||
* [`speechSynthesis.md`](#speechsynthesis.md)
|
||||
* [`binarySearch.md`](#binarysearch.md)
|
||||
@ -1309,6 +1572,9 @@ const fibonacciUntilNum = num => {
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
|
||||
```
|
||||
@ -1317,3 +1583,252 @@ fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### httpDelete
|
||||
|
||||
Makes a `DELETE` request to the passed URL.
|
||||
|
||||
Use `XMLHttpRequest` web api to make a `delete` request to the given `url`.
|
||||
Handle the `onload` event, by running the provided `callback` function.
|
||||
Handle the `onerror` event, by running the provided `err` function.
|
||||
Omit the third argument, `err` to log the request to the console's error stream by default.
|
||||
|
||||
```js
|
||||
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();
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
httpDelete('https://website.com/users/123', request => {
|
||||
console.log(request.responseText);
|
||||
}); // 'Deletes a user from the database'
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### httpPut
|
||||
|
||||
Makes a `PUT` request to the passed URL.
|
||||
|
||||
Use `XMLHttpRequest` web api to make a `put` request to the given `url`.
|
||||
Set the value of an `HTTP` request header with `setRequestHeader` method.
|
||||
Handle the `onload` event, by running the provided `callback` function.
|
||||
Handle the `onerror` event, by running the provided `err` function.
|
||||
Omit the last argument, `err` to log the request to the console's error stream by default.
|
||||
|
||||
```js
|
||||
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);
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
const password = "fooBaz";
|
||||
const data = JSON.stringify(password);
|
||||
httpPut('https://website.com/users/123', data, request => {
|
||||
console.log(request.responseText);
|
||||
}); // 'Updates a user's password in database'
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### isArmstrongNumber
|
||||
|
||||
Checks if the given number is an Armstrong number or not.
|
||||
|
||||
Convert 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`.
|
||||
|
||||
```js
|
||||
const isArmstrongNumber = digits =>
|
||||
(arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
|
||||
(digits + '').split('')
|
||||
);
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
isArmstrongNumber(1634); // true
|
||||
isArmstrongNumber(56); // false
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### quickSort
|
||||
|
||||
QuickSort an Array (ascending sort by default).
|
||||
|
||||
Use recursion.
|
||||
Use `Array.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.
|
||||
If the parameter `desc` is truthy, return array sorts in descending order.
|
||||
|
||||
```js
|
||||
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)
|
||||
];
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
quickSort([4, 1, 3, 2]); // [1,2,3,4]
|
||||
quickSort([4, 1, 3, 2], true); // [4,3,2,1]
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### removeVowels
|
||||
|
||||
Returns all the vowels in a `str` replaced by `repl`.
|
||||
|
||||
Use `String.replace()` with a regexp to replace all vowels in `str`.
|
||||
Omot `repl` to use a default value of `''`.
|
||||
|
||||
```js
|
||||
const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl);
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
removeVowels("foobAr"); // "fbr"
|
||||
removeVowels("foobAr","*"); // "f**b*r"
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### solveRPN
|
||||
|
||||
Solves the given mathematical expression in [reverse polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation).
|
||||
Throws 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.
|
||||
|
||||
Use a dictionary, `OPERATORS` to specify each operator's matching mathematical operation.
|
||||
Use `String.replace()` with a regular expression to replace `^` with `**`, `String.split()` to tokenize the string and `Array.filter()` to remove empty tokens.
|
||||
Use `Array.forEach()` to parse each `symbol`, evaluate it as a numeric value or operator and solve the mathematical expression.
|
||||
Numeric 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.
|
||||
|
||||
```js
|
||||
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`;
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
solveRPN('15 7 1 1 + - / 3 * 2 1 1 + + -'); // 5
|
||||
solveRPN('2 3 ^'); // 8
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
### howManyTimes
|
||||
|
||||
Returns the number of times `num` can be divided by `divisor` (integer or fractional) without getting a fractional answer.
|
||||
Works for both negative and positive integers.
|
||||
|
||||
If `divisor` is `-1` or `1` return `Infinity`.
|
||||
If `divisor` is `-0` or `0` return `0`.
|
||||
Otherwise, keep dividing `num` with `divisor` and incrementing `i`, while the result is an integer.
|
||||
Return the number of times the loop was executed, `i`.
|
||||
|
||||
```js
|
||||
const howManyTimes = (num, divisor) => {
|
||||
if (divisor === 1 || divisor === -1) return Infinity;
|
||||
if (divisor === 0) return 0;
|
||||
let i = 0;
|
||||
while (Number.isInteger(num / divisor)) {
|
||||
i++;
|
||||
num = num / divisor;
|
||||
}
|
||||
return i;
|
||||
};
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Examples</summary>
|
||||
|
||||
```js
|
||||
howManyTimes(100, 2); // 2
|
||||
howManyTimes(100, 2.5); // 2
|
||||
howManyTimes(100, 0); // 0
|
||||
howManyTimes(100, -1); // Infinity
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<br>[⬆ Back to top](#table-of-contents)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user