Travis build: 1297 [cron]

This commit is contained in:
30secondsofcode
2018-01-17 20:11:19 +00:00
parent ff003c12a4
commit 2f29187eea
13 changed files with 1575 additions and 1370 deletions

126
dist/_30s.es5.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

55
dist/_30s.esm.js vendored
View File

@ -4,6 +4,16 @@ const JSONToFile = (obj, filename) =>
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
const URLJoin = (...args) =>
args
.join('/')
.replace(/[\/]+/g, '/')
.replace(/^(.+):\//, '$1://')
.replace(/^file:/, 'file:/')
.replace(/\/(\?|&|#[^!])/g, '$1')
.replace(/\?/g, '&')
.replace('&', '?');
const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
@ -178,8 +188,6 @@ const digitize = n => [...`${n}`].map(i => parseInt(i));
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
const distinctValuesOfArray = arr => [...new Set(arr)];
const dropElements = (arr, func) => {
while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
return arr;
@ -351,6 +359,30 @@ const hasClass = (el, className) => el.classList.contains(className);
const hasFlags = (...flags) =>
flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));
const hashBrowser = val =>
crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => {
let hexes = [],
view = new DataView(h);
for (let i = 0; i < view.byteLength; i += 4)
hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
return hexes.join('');
});
const crypto$2 = typeof require !== "undefined" && require('crypto');
const hashNode = val =>
new Promise(resolve =>
setTimeout(
() =>
resolve(
crypto$2
.createHash('sha256')
.update(val)
.digest('hex')
),
0
)
);
const head = arr => arr[0];
const hexToRGB = hex => {
@ -383,7 +415,7 @@ const httpGet = (url, callback, err = console.error) => {
request.send();
};
const httpPost = (url, callback, data = null, err = console.error) => {
const httpPost = (url, data, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
@ -415,6 +447,11 @@ const initialize2DArray = (w, h, val = null) =>
const initializeArrayWithRange = (end, start = 0, step = 1) =>
Array.from({ length: Math.ceil((end + 1 - start) / step) }).map((v, i) => i * step + start);
const initializeArrayWithRangeRight = (end, start = 0, step = 1) =>
Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(
(v, i, arr) => (arr.length - i - 1) * step + start
);
const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
const intersection = (a, b) => {
@ -428,9 +465,9 @@ const invertKeyValues = obj =>
return acc;
}, {});
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
const is = (type, val) => val instanceof type;
const isArray = val => Array.isArray(val);
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
const isArrayLike = val => {
try {
@ -450,6 +487,8 @@ const isFunction = val => typeof val === 'function';
const isLowerCase = str => str === str.toLowerCase();
const isNil = val => val === undefined || val === null;
const isNull = val => val === null;
const isNumber = val => typeof val === 'number';
@ -482,6 +521,8 @@ const isSymbol = val => typeof val === 'symbol';
const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
const isUndefined = val => val === undefined;
const isUpperCase = str => str === str.toUpperCase();
const isValidJSON = obj => {
@ -980,6 +1021,8 @@ const unescapeHTML = str =>
const union = (a, b) => Array.from(new Set([...a, ...b]));
const uniqueElements = arr => [...new Set(arr)];
const untildify = str => str.replace(/^~($|\/|\\)/, `${typeof require !== "undefined" && require('os').homedir()}$1`);
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
@ -1001,6 +1044,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,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,observeMutations,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,}
var imports = {JSONToFile,RGBToHex,URLJoin,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,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,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,inRange,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,intersection,invertKeyValues,is,isAbsoluteURL,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isLowerCase,isNil,isNull,isNumber,isObject,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapValues,mask,maxBy,maxN,median,memoize,merge,minBy,minN,negate,nthElement,objectFromPairs,objectToPairs,observeMutations,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,uniqueElements,untildify,validateNumber,without,words,yesNo,zip,zipObject,}
export default imports;

55
dist/_30s.js vendored
View File

@ -10,6 +10,16 @@ const JSONToFile = (obj, filename) =>
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
const URLJoin = (...args) =>
args
.join('/')
.replace(/[\/]+/g, '/')
.replace(/^(.+):\//, '$1://')
.replace(/^file:/, 'file:/')
.replace(/\/(\?|&|#[^!])/g, '$1')
.replace(/\?/g, '&')
.replace('&', '?');
const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
@ -184,8 +194,6 @@ const digitize = n => [...`${n}`].map(i => parseInt(i));
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
const distinctValuesOfArray = arr => [...new Set(arr)];
const dropElements = (arr, func) => {
while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
return arr;
@ -357,6 +365,30 @@ const hasClass = (el, className) => el.classList.contains(className);
const hasFlags = (...flags) =>
flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag));
const hashBrowser = val =>
crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => {
let hexes = [],
view = new DataView(h);
for (let i = 0; i < view.byteLength; i += 4)
hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
return hexes.join('');
});
const crypto$2 = typeof require !== "undefined" && require('crypto');
const hashNode = val =>
new Promise(resolve =>
setTimeout(
() =>
resolve(
crypto$2
.createHash('sha256')
.update(val)
.digest('hex')
),
0
)
);
const head = arr => arr[0];
const hexToRGB = hex => {
@ -389,7 +421,7 @@ const httpGet = (url, callback, err = console.error) => {
request.send();
};
const httpPost = (url, callback, data = null, err = console.error) => {
const httpPost = (url, data, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
@ -421,6 +453,11 @@ const initialize2DArray = (w, h, val = null) =>
const initializeArrayWithRange = (end, start = 0, step = 1) =>
Array.from({ length: Math.ceil((end + 1 - start) / step) }).map((v, i) => i * step + start);
const initializeArrayWithRangeRight = (end, start = 0, step = 1) =>
Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(
(v, i, arr) => (arr.length - i - 1) * step + start
);
const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val);
const intersection = (a, b) => {
@ -434,9 +471,9 @@ const invertKeyValues = obj =>
return acc;
}, {});
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
const is = (type, val) => val instanceof type;
const isArray = val => Array.isArray(val);
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
const isArrayLike = val => {
try {
@ -456,6 +493,8 @@ const isFunction = val => typeof val === 'function';
const isLowerCase = str => str === str.toLowerCase();
const isNil = val => val === undefined || val === null;
const isNull = val => val === null;
const isNumber = val => typeof val === 'number';
@ -488,6 +527,8 @@ const isSymbol = val => typeof val === 'symbol';
const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env;
const isUndefined = val => val === undefined;
const isUpperCase = str => str === str.toUpperCase();
const isValidJSON = obj => {
@ -986,6 +1027,8 @@ const unescapeHTML = str =>
const union = (a, b) => Array.from(new Set([...a, ...b]));
const uniqueElements = arr => [...new Set(arr)];
const untildify = str => str.replace(/^~($|\/|\\)/, `${typeof require !== "undefined" && require('os').homedir()}$1`);
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
@ -1007,7 +1050,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,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,observeMutations,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,}
var imports = {JSONToFile,RGBToHex,URLJoin,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,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,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,inRange,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,intersection,invertKeyValues,is,isAbsoluteURL,isArrayLike,isBoolean,isDivisible,isEven,isFunction,isLowerCase,isNil,isNull,isNumber,isObject,isPrime,isPrimitive,isPromiseLike,isSorted,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapObject,mapValues,mask,maxBy,maxN,median,memoize,merge,minBy,minN,negate,nthElement,objectFromPairs,objectToPairs,observeMutations,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,uniqueElements,untildify,validateNumber,without,words,yesNo,zip,zipObject,}
return imports;

2
dist/_30s.min.js vendored

File diff suppressed because one or more lines are too long

View File

@ -6,24 +6,78 @@ These snippets, while useful and interesting, didn't quite make it into the repo
## Table of Contents
* [`binarySearch`](#binarysearch)
* [`JSONToDate`](#jsontodate)
* [`speechSynthesis`](#speechsynthesis)
* [`binarySearch`](#binarysearch)
* [`collatz`](#collatz)
* [`countVowels`](#countvowels)
* [`factors`](#factors)
* [`fibonacciCountUntilNum`](#fibonaccicountuntilnum)
* [`fibonacciUntilNum`](#fibonacciuntilnum)
* [`howManyTimes`](#howmanytimes)
* [`httpDelete`](#httpdelete)
* [`collatz`](#collatz)
* [`httpPut`](#httpput)
* [`isArmstrongNumber`](#isarmstrongnumber)
* [`JSONToDate`](#jsontodate)
* [`quickSort`](#quicksort)
* [`removeVowels`](#removevowels)
* [`solveRPN`](#solverpn)
* [`httpPut`](#httpput)
* [`howManyTimes`](#howmanytimes)
---
### 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.
@ -57,28 +111,21 @@ binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1
<br>[⬆ Back to top](#table-of-contents)
### speechSynthesis
### collatz
Performs speech synthesis (experimental).
Applies the Collatz algorithm.
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).
If `n` is even, return `n/2`. Otherwise, return `3n+1`.
```js
const speechSynthesis = message => {
const msg = new SpeechSynthesisUtterance(message);
msg.voice = window.speechSynthesis.getVoices()[0];
window.speechSynthesis.speak(msg);
};
const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1);
```
<details>
<summary>Examples</summary>
```js
speechSynthesis('Hello, World'); // // plays the message
collatz(8); // 4
```
</details>
@ -213,44 +260,6 @@ fibonacciUntilNum(10); // [ 0, 1, 1, 2, 3, 5, 8 ]
<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)
### httpDelete
Makes a `DELETE` request to the passed URL.
@ -284,21 +293,36 @@ httpDelete('https://website.com/users/123', request => {
<br>[⬆ Back to top](#table-of-contents)
### collatz
### httpPut
Applies the Collatz algorithm.
Makes a `PUT` request to the passed URL.
If `n` is even, return `n/2`. Otherwise, return `3n+1`.
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 collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1);
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
collatz(8); // 4
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>
@ -332,31 +356,6 @@ isArmstrongNumber(56); // false
<br>[⬆ Back to top](#table-of-contents)
### 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)
### quickSort
QuickSort an Array (ascending sort by default).
@ -467,24 +466,26 @@ solveRPN('2 3 ^'); // 8
<br>[⬆ Back to top](#table-of-contents)
### httpPut
### howManyTimes
Makes a `PUT` request to the passed URL.
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.
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.
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 httpPut = (url, data, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open("PUT", url, true);
request.setRequestHeader('Content-type','application/json; charset=utf-8');
request.onload = () => callback(request);
request.onerror = () => err(request);
request.send(data);
const 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;
};
```
@ -492,11 +493,10 @@ const httpPut = (url, data, callback, err = console.error) => {
<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'
howManyTimes(100, 2); // 2
howManyTimes(100, 2.5); // 2
howManyTimes(100, 0); // 0
howManyTimes(100, -1); // Infinity
```
</details>

View File

@ -0,0 +1,9 @@
const hashBrowser = val =>
crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h => {
let hexes = [],
view = new DataView(h);
for (let i = 0; i < view.byteLength; i += 4)
hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
return hexes.join('');
});
module.exports = hashBrowser

View File

@ -0,0 +1,13 @@
const test = require('tape');
const hashBrowser = require('./hashBrowser.js');
test('Testing hashBrowser', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof hashBrowser === 'function', 'hashBrowser is a Function');
//t.deepEqual(hashBrowser(args..), 'Expected');
//t.equal(hashBrowser(args..), 'Expected');
//t.false(hashBrowser(args..), 'Expected');
//t.throws(hashBrowser(args..), 'Expected');
t.end();
});

15
test/hashNode/hashNode.js Normal file
View File

@ -0,0 +1,15 @@
const crypto = require('crypto');
const hashNode = val =>
new Promise(resolve =>
setTimeout(
() =>
resolve(
crypto
.createHash('sha256')
.update(val)
.digest('hex')
),
0
)
);
module.exports = hashNode

View File

@ -0,0 +1,13 @@
const test = require('tape');
const hashNode = require('./hashNode.js');
test('Testing hashNode', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof hashNode === 'function', 'hashNode is a Function');
//t.deepEqual(hashNode(args..), 'Expected');
//t.equal(hashNode(args..), 'Expected');
//t.false(hashNode(args..), 'Expected');
//t.throws(hashNode(args..), 'Expected');
t.end();
});

2
test/is/is.js Normal file
View File

@ -0,0 +1,2 @@
const is = (type, val) => val instanceof type;
module.exports = is

13
test/is/is.test.js Normal file
View File

@ -0,0 +1,13 @@
const test = require('tape');
const is = require('./is.js');
test('Testing is', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof is === 'function', 'is is a Function');
//t.deepEqual(is(args..), 'Expected');
//t.equal(is(args..), 'Expected');
//t.false(is(args..), 'Expected');
//t.throws(is(args..), 'Expected');
t.end();
});

File diff suppressed because it is too large Load Diff