Travis build: 1012

This commit is contained in:
30secondsofcode
2019-02-23 10:50:43 +00:00
parent 9c607d00f2
commit 240e38b4a0
23 changed files with 3504 additions and 3512 deletions

View File

@ -669,14 +669,13 @@ const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Pr
<summary>Examples</summary>
```js
const sum = pipeAsyncFunctions(
x => x + 1,
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
x => x + 3,
async x => (await x) + 4
);
(async() => {
(async () => {
console.log(await sum(5)); // 15 (after one second)
})();
```
@ -2318,13 +2317,12 @@ Use `Array.prototype.filter()` to find array elements that return truthy values
The `func` is invoked with three arguments (`value, index, array`).
```js
const remove = (arr, func) =>
Array.isArray(arr)
? arr.filter(func).reduce((acc, val) => {
arr.splice(arr.indexOf(val), 1);
return acc.concat(val);
}, [])
arr.splice(arr.indexOf(val), 1);
return acc.concat(val);
}, [])
: [];
```
@ -5502,12 +5500,11 @@ Otherwise, return the product of `n` and the factorial of `n - 1`.
Throws an exception if `n` is a negative number.
```js
const factorial = n =>
n < 0
? (() => {
throw new TypeError('Negative numbers are not allowed!');
})()
throw new TypeError('Negative numbers are not allowed!');
})()
: n <= 1
? 1
: n * factorial(n - 1);
@ -5817,14 +5814,16 @@ Maps a number from one range to another range.
Returns `num` mapped between `outMin`-`outMax` from `inMin`-`inMax`.
```js
const mapNumRange = (num, inMin, inMax, outMin, outMax) => (num - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
const mapNumRange = (num, inMin, inMax, outMin, outMax) =>
((num - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
```
<details>
<summary>Examples</summary>
```js
mapNumRange(5,0,10,0,100); // 50
mapNumRange(5, 0, 10, 0, 100); // 50
```
</details>
@ -6778,17 +6777,16 @@ Use `Object.keys(obj)` to iterate over the object's keys.
Use `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`.
```js
const deepMapKeys = (obj, f) =>
Array.isArray(obj)
? obj.map(val => deepMapKeys(val, f))
: typeof obj === 'object'
? Object.keys(obj).reduce((acc, current) => {
const val = obj[current];
acc[f(current)] =
const val = obj[current];
acc[f(current)] =
val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);
return acc;
}, {})
return acc;
}, {})
: obj;
```
@ -6858,14 +6856,13 @@ Use the `in` operator to check if `target` exists in `obj`.
If found, return the value of `obj[target]`, otherwise use `Object.values(obj)` and `Array.prototype.reduce()` to recursively call `dig` on each nested object until the first matching key/value pair is found.
```js
const dig = (obj, target) =>
target in obj
? obj[target]
: Object.values(obj).reduce((acc, val) => {
if (acc !== undefined) return acc;
if (typeof val === 'object') return dig(val, target);
}, undefined);
if (acc !== undefined) return acc;
if (typeof val === 'object') return dig(val, target);
}, undefined);
```
<details>

View File

@ -339,6 +339,7 @@
<li><a tags="math,beginner,intermediate" href="./math#isprime">isPrime</a></li>
<li><a tags="math,recursion,beginner" href="./math#lcm">lcm</a></li>
<li><a tags="math,utility,advanced" href="./math#luhncheck">luhnCheck</a></li>
<li><a tags="math,beginner" href="./math#mapnumrange">mapNumRange</a></li>
<li><a tags="math,array,function,beginner" href="./math#maxby">maxBy</a></li>
<li><a tags="math,array,intermediate" href="./math#median">median</a></li>
<li><a tags="math,array,beginner" href="./math#midpoint">midpoint</a></li>

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

@ -339,6 +339,7 @@
<li><a tags="math,beginner,intermediate" href="./math#isprime">isPrime</a></li>
<li><a tags="math,recursion,beginner" href="./math#lcm">lcm</a></li>
<li><a tags="math,utility,advanced" href="./math#luhncheck">luhnCheck</a></li>
<li><a tags="math,beginner" href="./math#mapnumrange">mapNumRange</a></li>
<li><a tags="math,array,function,beginner" href="./math#maxby">maxBy</a></li>
<li><a tags="math,array,intermediate" href="./math#median">median</a></li>
<li><a tags="math,array,beginner" href="./math#midpoint">midpoint</a></li>

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

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

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

File diff suppressed because one or more lines are too long

View File

@ -8,17 +8,16 @@ Use `Object.keys(obj)` to iterate over the object's keys.
Use `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`.
```js
const deepMapKeys = (obj, f) =>
Array.isArray(obj)
? obj.map(val => deepMapKeys(val, f))
: typeof obj === 'object'
? Object.keys(obj).reduce((acc, current) => {
const val = obj[current];
acc[f(current)] =
const val = obj[current];
acc[f(current)] =
val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);
return acc;
}, {})
return acc;
}, {})
: obj;
```

View File

@ -6,14 +6,13 @@ Use the `in` operator to check if `target` exists in `obj`.
If found, return the value of `obj[target]`, otherwise use `Object.values(obj)` and `Array.prototype.reduce()` to recursively call `dig` on each nested object until the first matching key/value pair is found.
```js
const dig = (obj, target) =>
target in obj
? obj[target]
: Object.values(obj).reduce((acc, val) => {
if (acc !== undefined) return acc;
if (typeof val === 'object') return dig(val, target);
}, undefined);
if (acc !== undefined) return acc;
if (typeof val === 'object') return dig(val, target);
}, undefined);
```
```js

View File

@ -8,12 +8,11 @@ Otherwise, return the product of `n` and the factorial of `n - 1`.
Throws an exception if `n` is a negative number.
```js
const factorial = n =>
n < 0
? (() => {
throw new TypeError('Negative numbers are not allowed!');
})()
throw new TypeError('Negative numbers are not allowed!');
})()
: n <= 1
? 1
: n * factorial(n - 1);

View File

@ -5,9 +5,11 @@ Maps a number from one range to another range.
Returns `num` mapped between `outMin`-`outMax` from `inMin`-`inMax`.
```js
const mapNumRange = (num, inMin, inMax, outMin, outMax) => (num - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
const mapNumRange = (num, inMin, inMax, outMin, outMax) =>
((num - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
```
```js
mapNumRange(5,0,10,0,100); // 50
mapNumRange(5, 0, 10, 0, 100); // 50
```

View File

@ -11,14 +11,13 @@ const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Pr
```
```js
const sum = pipeAsyncFunctions(
x => x + 1,
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
x => x + 3,
async x => (await x) + 4
);
(async() => {
(async () => {
console.log(await sum(5)); // 15 (after one second)
})();
```

View File

@ -6,13 +6,12 @@ Use `Array.prototype.filter()` to find array elements that return truthy values
The `func` is invoked with three arguments (`value, index, array`).
```js
const remove = (arr, func) =>
Array.isArray(arr)
? arr.filter(func).reduce((acc, val) => {
arr.splice(arr.indexOf(val), 1);
return acc.concat(val);
}, [])
arr.splice(arr.indexOf(val), 1);
return acc.concat(val);
}, [])
: [];
```

View File

@ -1,6 +1,53 @@
const fs = typeof require !== "undefined" && require('fs');
const crypto = typeof require !== "undefined" && require('crypto');
const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
data
.slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
.split('\n')
.map(v => v.split(delimiter));
const CSVToJSON = (data, delimiter = ',') => {
const titles = data.slice(0, data.indexOf('\n')).split(delimiter);
return data
.slice(data.indexOf('\n') + 1)
.split('\n')
.map(v => {
const values = v.split(delimiter);
return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
});
};
const JSONToFile = (obj, filename) =>
fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
const JSONtoCSV = (arr, columns, delimiter = ',') =>
[
columns.join(delimiter),
...arr.map(obj =>
columns.reduce(
(acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`,
''
)
)
].join('\n');
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
const URLJoin = (...args) =>
args
.join('/')
.replace(/[\/]+/g, '/')
.replace(/^(.+):\//, '$1://')
.replace(/^file:/, 'file:/')
.replace(/\/(\?|&|#[^!])/g, '$1')
.replace(/\?/g, '&')
.replace('&', '?');
const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
);
const UUIDGeneratorNode = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
);
const all = (arr, fn = Boolean) => arr.every(fn);
const allEqual = arr => arr.every(val => val === arr[0]);
const any = (arr, fn = Boolean) => arr.some(fn);
@ -124,6 +171,7 @@ const countBy = (arr, fn) =>
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
const counter = (selector, start, end, step = 1, duration = 2000) => {
let current = start,
_step = (end - start) * step < 0 ? -step : step,
@ -135,7 +183,6 @@ const counter = (selector, start, end, step = 1, duration = 2000) => {
}, Math.abs(Math.floor(duration / (end - start))));
return timer;
};
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
const createElement = str => {
@ -157,21 +204,6 @@ const createEventHub = () => ({
if (i > -1) this.hub[event].splice(i, 1);
}
});
const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
data
.slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
.split('\n')
.map(v => v.split(delimiter));
const CSVToJSON = (data, delimiter = ',') => {
const titles = data.slice(0, data.indexOf('\n')).split(delimiter);
return data
.slice(data.indexOf('\n') + 1)
.split('\n')
.map(v => {
const values = v.split(delimiter);
return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
});
};
const currentURL = () => window.location.href;
const curry = (fn, arity = fn.length, ...args) =>
arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
@ -203,17 +235,16 @@ const deepFreeze = obj =>
prop =>
!(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])
) || Object.freeze(obj);
const deepMapKeys = (obj, f) =>
Array.isArray(obj)
? obj.map(val => deepMapKeys(val, f))
: typeof obj === 'object'
? Object.keys(obj).reduce((acc, current) => {
? Object.keys(obj).reduce((acc, current) => {
const val = obj[current];
const val = obj[current];
acc[f(current)] =
val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);
val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);
return acc;
return acc;
}, {})
: obj;
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
@ -232,14 +263,13 @@ const differenceBy = (a, b, fn) => {
return a.filter(x => !s.has(fn(x)));
};
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
const dig = (obj, target) =>
target in obj
? obj[target]
: Object.values(obj).reduce((acc, val) => {
? obj[target]
: Object.values(obj).reduce((acc, val) => {
if (acc !== undefined) return acc;
if (acc !== undefined) return acc;
if (typeof val === 'object') return dig(val, target);
}, undefined);
const digitize = n => [...`${n}`].map(i => parseInt(i));
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
const drop = (arr, n = 1) => arr.slice(n);
@ -308,12 +338,11 @@ const extendHex = shortHex =>
.split('')
.map(x => x + x)
.join('');
.map(x => x + x)
const factorial = n =>
n < 0
? (() => {
const factorial = n =>
n < 0
throw new TypeError('Negative numbers are not allowed!');
})()
: n <= 1
? 1
: n * factorial(n - 1);
@ -352,6 +381,11 @@ const forEachRight = (arr, callback) =>
.slice(0)
.reverse()
.forEach(callback);
const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
const forOwnRight = (obj, fn) =>
Object.keys(obj)
.reverse()
.forEach(key => fn(obj[key], key, obj));
const formatDuration = ms => {
if (ms < 0) ms = -ms;
const time = {
@ -366,11 +400,6 @@ const formatDuration = ms => {
.map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
.join(', ');
};
.map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
.join(', ');
};
const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
const forOwnRight = (obj, fn) =>
const fromCamelCase = (str, separator = '_') =>
str
.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
@ -500,6 +529,10 @@ const hz = (fn, iterations = 100) => {
for (let i = 0; i < iterations; i++) fn();
return (1000 * iterations) / (performance.now() - before);
};
const inRange = (n, start, end = null) => {
if (end && start > end) [end, start] = [start, end];
return end == null ? n >= 0 && n < start : n >= start && n < end;
};
const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count));
const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);
const initial = arr => arr.slice(0, -1);
@ -516,10 +549,6 @@ const initializeNDArray = (val, ...args) =>
args.length === 0
? val
: Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1)));
const initializeNDArray = (val, ...args) =>
args.length === 0
? val
: Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1)));
const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);
const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);
const intersection = (a, b) => {
@ -631,19 +660,6 @@ const join = (arr, separator = ',', end = separator) =>
: acc + val + separator,
''
);
? acc + val
: acc + val + separator,
''
);
const JSONtoCSV = (arr, columns, delimiter = ',') =>
[
columns.join(delimiter),
...arr.map(obj =>
columns.reduce(
(acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`,
''
)
)
const last = arr => arr[arr.length - 1];
const lcm = (...arr) => {
const gcd = (x, y) => (!y ? x : gcd(y, x % y));
@ -671,7 +687,8 @@ const mapKeys = (obj, fn) =>
acc[fn(obj[k], k, obj)] = obj[k];
return acc;
}, {});
Object.keys(obj).reduce((acc, k) => {
const mapNumRange = (num, inMin, inMax, outMin, outMax) =>
((num - inMin) * (outMax - outMin)) / (inMax - inMin) + outMin;
const mapObject = (arr, fn) =>
(a => (
(a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
@ -777,14 +794,6 @@ const on = (el, evt, fn, opts = {}) => {
el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false);
if (opts.target) return delegatorFn;
};
const on = (el, evt, fn, opts = {}) => {
const delegatorFn = e => e.target.matches(opts.target) && fn.call(e.target, e);
el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false);
if (opts.target) return delegatorFn;
};
const once = fn => {
let called = false;
return function(...args) {
const onUserInputChange = callback => {
let type = 'mouse',
lastTime = 0;
@ -799,6 +808,14 @@ const onUserInputChange = callback => {
(type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler);
});
};
const once = fn => {
let called = false;
return function(...args) {
if (called) return;
called = true;
return fn.apply(this, args);
};
};
const orderBy = (arr, props, orders) =>
[...arr].sort((a, b) =>
props.reduce((acc, prop, i) => {
@ -853,7 +870,7 @@ const pickBy = (obj, fn) =>
Object.keys(obj)
.filter(k => fn(obj[k], k))
.reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {});
const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Promise.resolve(arg));
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
const pluralize = (val, word, plural = word + 's') => {
const _pluralize = (num, word, plural = word + 's') =>
@ -958,6 +975,10 @@ const recordAnimationFrames = (callback, autoStart = true) => {
};
const redirect = (url, asLink = true) =>
asLink ? (window.location.href = url) : window.location.replace(url);
const reduceSuccessive = (arr, fn, acc) =>
arr.reduce((res, val, i, arr) => (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]);
const reduceWhich = (arr, comparator = (a, b) => a - b) =>
arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a));
const reducedFilter = (data, keys, fn) =>
data.filter(fn).map(el =>
keys.reduce((acc, key) => {
@ -965,18 +986,13 @@ const reducedFilter = (data, keys, fn) =>
return acc;
}, {})
);
data.filter(fn).map(el =>
keys.reduce((acc, key) => {
acc[key] = el[key];
return acc;
const reject = (pred, array) => array.filter((...args) => !pred(...args));
);
const remove = (arr, func) =>
Array.isArray(arr)
? arr.filter(func).reduce((acc, val) => {
arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a));
const reject = (pred, array) => array.filter((...args) => !pred(...args));
arr.splice(arr.indexOf(val), 1);
return acc.concat(val);
}, [])
: [];
const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');
const renameKeys = (keysMap, obj) =>
@ -988,7 +1004,6 @@ const renameKeys = (keysMap, obj) =>
{}
);
const reverseString = str => [...str].reverse().join('');
(acc, key) => ({
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
const runAsync = fn => {
const worker = new Worker(
@ -1163,16 +1178,16 @@ const throttle = (fn, wait) => {
}
};
};
fn.apply(context, args);
lastTime = Date.now();
}
}, Math.max(wait - (Date.now() - lastTime), 0));
const timeTaken = callback => {
console.time('timeTaken');
const r = callback();
console.timeEnd('timeTaken');
return r;
};
const times = (n, fn, context = undefined) => {
let i = 0;
while (fn.call(context, i) !== false && ++i < n) {}
};
const toCamelCase = str => {
let s =
str &&
@ -1185,7 +1200,6 @@ const toCamelCase = str => {
const toCurrency = (n, curr, LanguageFormat = undefined) =>
Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
const toDecimalMark = num => num.toLocaleString('en-US');
.map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
const toHash = (object, key) =>
Array.prototype.reduce.call(
object,
@ -1198,11 +1212,6 @@ const toKebabCase = str =>
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.toLowerCase())
.join('-');
);
const toKebabCase = str =>
str &&
str
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
const toOrdinalSuffix = num => {
const int = parseInt(num),
digits = [int % 10, int % 100],
@ -1226,6 +1235,12 @@ const toTitleCase = str =>
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map(x => x.charAt(0).toUpperCase() + x.slice(1))
.join(' ');
const toggleClass = (el, className) => el.classList.toggle(className);
const tomorrow = () => {
let t = new Date();
t.setDate(t.getDate() + 1);
return t.toISOString().split('T')[0];
};
const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
const triggerEvent = (el, eventType, detail) =>
el.dispatchEvent(new CustomEvent(eventType, { detail }));
@ -1310,24 +1325,6 @@ const unzipWith = (arr, fn) =>
}).map(x => [])
)
.map(val => fn(...val));
.reduce(
(acc, val) => (val.forEach((v, i) => acc[i].push(v)), acc),
Array.from({
length: Math.max(...arr.map(x => x.length))
}).map(x => [])
)
.map(val => fn(...val));
const URLJoin = (...args) =>
args
.join('/')
.replace(/[\/]+/g, '/')
.replace(/^(.+):\//, '$1://')
.replace(/^file:/, 'file:/')
.replace(/\/(\?|&|#[^!])/g, '$1')
.replace(/\?/g, '&')
.replace('&', '?');
const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x);
const without = (arr, ...args) => arr.filter(v => !args.includes(v));
@ -1350,15 +1347,19 @@ const zipWith = (...array) => {
(_, i) => (fn ? fn(...array.map(a => a[i])) : array.map(a => a[i]))
);
};
const zipWith = (...array) => {
const JSONToDate = arr => {
const dt = new Date(parseInt(arr.toString().substr(6)));
return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
};
const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
if (start > end) return -1;
const mid = Math.floor((start + end) / 2);
if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);
if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);
return mid;
};
const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
const celsiusToFahrenheit = degrees => 1.8 * degrees + 32;
const cleanObj = (obj, keysToKeep = [], childIndicator) => {
Object.keys(obj).forEach(key => {
if (key === childIndicator) {
cleanObj(obj[key], keysToKeep, childIndicator);
@ -1368,9 +1369,9 @@ const zipWith = (...array) => {
});
return obj;
};
const cleanObj = (obj, keysToKeep = [], childIndicator) => {
Object.keys(obj).forEach(key => {
if (key === childIndicator) {
const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);
const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
const factors = (num, primes = false) => {
const isPrime = num => {
const boundary = Math.floor(Math.sqrt(num));
for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
@ -1389,21 +1390,21 @@ const zipWith = (...array) => {
}, []);
return primes ? array.filter(isPrime) : array;
};
const isNeg = num < 0;
num = isNeg ? -num : num;
const fahrenheitToCelsius = degrees => (degrees - 32) * 5/9;
const fibonacciCountUntilNum = num =>
Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
.map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))
const fibonacciUntilNum = num => {
let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
return Array.from({ length: n }).reduce(
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
[]
);
};
}, []);
const heronArea = (side_a, side_b, side_c) => {
const p = (side_a + side_b + side_c) / 2
return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))
};
const fahrenheitToCelsius = degrees => (degrees - 32) * 5/9;
const howManyTimes = (num, divisor) => {
if (divisor === 1 || divisor === -1) return Infinity;
if (divisor === 0) return 0;
let i = 0;
@ -1413,14 +1414,14 @@ const zipWith = (...array) => {
}
return i;
};
);
const httpDelete = (url, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open('DELETE', url, true);
request.onload = () => callback(request);
request.onerror = () => err(request);
request.send();
};
const httpPut = (url, data, callback, err = console.error) => {
const request = new XMLHttpRequest();
request.open("PUT", url, true);
request.setRequestHeader('Content-type','application/json; charset=utf-8');
@ -1428,11 +1429,11 @@ const zipWith = (...array) => {
request.onerror = () => err(request);
request.send(data);
};
}
const isArmstrongNumber = digits =>
(arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
(digits + '').split('')
);
const httpDelete = (url, callback, err = console.error) => {
const isSimilar = (pattern, str) =>
[...str].reduce(
(matchIndex, char) =>
char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase()
@ -1440,12 +1441,8 @@ const zipWith = (...array) => {
: matchIndex,
0
) === pattern.length;
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);
const kmphToMph = (kmph) => 0.621371192 * kmph;
const levenshteinDistance = (string1, string2) => {
if (string1.length === 0) return string2.length;
if (string2.length === 0) return string1.length;
let matrix = Array(string2.length + 1)
@ -1469,9 +1466,9 @@ const zipWith = (...array) => {
}
return matrix[string2.length][string1.length];
};
const levenshteinDistance = (string1, string2) => {
if (string1.length === 0) return string2.length;
const mphToKmph = (mph) => 1.6093440006146922 * mph;
const pipeLog = data => console.log(data) || data;
const quickSort = ([n, ...nums], desc) =>
isNaN(n)
? []
: [
@ -1479,8 +1476,8 @@ const zipWith = (...array) => {
n,
...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)
];
for (let i = 1; i <= string2.length; i++) {
for (let j = 1; j <= string1.length; j++) {
const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);
const solveRPN = rpn => {
const OPERATORS = {
'*': (a, b) => a * b,
'+': (a, b) => a + b,
@ -1508,12 +1505,12 @@ const zipWith = (...array) => {
if (stack.length === 1) return stack.pop();
else throw `${rpn} is not a proper RPN. Please check it and try again`;
};
const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);
const speechSynthesis = message => {
const msg = new SpeechSynthesisUtterance(message);
msg.voice = window.speechSynthesis.getVoices()[0];
window.speechSynthesis.speak(msg);
};
'+': (a, b) => a + b,
const squareSum = (...args) => args.reduce((squareSum, number) => squareSum + Math.pow(number, 2), 0);
'**': (a, b) => a ** b
module.exports = {CSVToArray,CSVToJSON,JSONToFile,JSONtoCSV,RGBToHex,URLJoin,UUIDGeneratorBrowser,UUIDGeneratorNode,all,allEqual,any,approximatelyEqual,arrayToCSV,arrayToHtmlList,ary,atob,attempt,average,averageBy,bifurcate,bifurcateBy,bind,bindAll,bindKey,binomialCoefficient,bottomVisible,btoa,byteSize,call,capitalize,capitalizeEveryWord,castArray,chainAsync,chunk,clampNumber,cloneRegExp,coalesce,coalesceFactory,collectInto,colorize,compact,compactWhitespace,compose,composeRight,converge,copyToClipboard,countBy,countOccurrences,counter,createDirIfNotExists,createElement,createEventHub,currentURL,curry,dayOfYear,debounce,decapitalize,deepClone,deepFlatten,deepFreeze,deepMapKeys,defaults,defer,degreesToRads,delay,detectDeviceType,difference,differenceBy,differenceWith,dig,digitize,distance,drop,dropRight,dropRightWhile,dropWhile,elementContains,elementIsVisibleInViewport,elo,equals,escapeHTML,escapeRegExp,everyNth,extendHex,factorial,fibonacci,filterFalsy,filterNonUnique,filterNonUniqueBy,findKey,findLast,findLastIndex,findLastKey,flatten,flattenObject,flip,forEachRight,forOwn,forOwnRight,formatDuration,fromCamelCase,functionName,functions,gcd,geometricProgression,get,getColonTimeFromDate,getDaysDiffBetweenDates,getImages,getMeridiemSuffixOfInteger,getScrollPosition,getStyle,getType,getURLParameters,groupBy,hammingDistance,hasClass,hasFlags,hashBrowser,hashNode,head,hexToRGB,hide,httpGet,httpPost,httpsRedirect,hz,inRange,indentString,indexOfAll,initial,initialize2DArray,initializeArrayWithRange,initializeArrayWithRangeRight,initializeArrayWithValues,initializeNDArray,insertAfter,insertBefore,intersection,intersectionBy,intersectionWith,invertKeyValues,is,isAbsoluteURL,isAfterDate,isAnagram,isArrayLike,isBeforeDate,isBoolean,isBrowser,isBrowserTabFocused,isDivisible,isDuplexStream,isEmpty,isEven,isFunction,isLowerCase,isNegativeZero,isNil,isNull,isNumber,isObject,isObjectLike,isPlainObject,isPrime,isPrimitive,isPromiseLike,isReadableStream,isSameDate,isSorted,isStream,isString,isSymbol,isTravisCI,isUndefined,isUpperCase,isValidJSON,isWritableStream,join,last,lcm,longestItem,lowercaseKeys,luhnCheck,mapKeys,mapNumRange,mapObject,mapString,mapValues,mask,matches,matchesWith,maxBy,maxDate,maxN,median,memoize,merge,midpoint,minBy,minDate,minN,mostPerformant,negate,nest,nodeListToArray,none,nthArg,nthElement,objectFromPairs,objectToPairs,observeMutations,off,offset,omit,omitBy,on,onUserInputChange,once,orderBy,over,overArgs,pad,palindrome,parseCookie,partial,partialRight,partition,percentile,permutations,pick,pickBy,pipeAsyncFunctions,pipeFunctions,pluralize,powerset,prefix,prettyBytes,primes,promisify,pull,pullAtIndex,pullAtValue,pullBy,radsToDegrees,randomHexColorCode,randomIntArrayInRange,randomIntegerInRange,randomNumberInRange,readFileLines,rearg,recordAnimationFrames,redirect,reduceSuccessive,reduceWhich,reducedFilter,reject,remove,removeNonASCII,renameKeys,reverseString,round,runAsync,runPromisesInSeries,sample,sampleSize,scrollToTop,sdbm,serializeCookie,setStyle,shallowClone,shank,show,shuffle,similarity,size,sleep,smoothScroll,sortCharactersInString,sortedIndex,sortedIndexBy,sortedLastIndex,sortedLastIndexBy,splitLines,spreadOver,stableSort,standardDeviation,stringPermutations,stripHTMLTags,sum,sumBy,sumPower,symmetricDifference,symmetricDifferenceBy,symmetricDifferenceWith,tail,take,takeRight,takeRightWhile,takeWhile,throttle,timeTaken,times,toCamelCase,toCurrency,toDecimalMark,toHash,toKebabCase,toOrdinalSuffix,toSafeInteger,toSnakeCase,toTitleCase,toggleClass,tomorrow,transform,triggerEvent,truncateString,truthCheckCollection,unary,uncurry,unescapeHTML,unflattenObject,unfold,union,unionBy,unionWith,uniqueElements,uniqueElementsBy,uniqueElementsByRight,uniqueSymmetricDifference,untildify,unzip,unzipWith,validateNumber,when,without,words,xProd,yesNo,zip,zipObject,zipWith,JSONToDate,binarySearch,celsiusToFahrenheit,cleanObj,collatz,countVowels,factors,fahrenheitToCelsius,fibonacciCountUntilNum,fibonacciUntilNum,heronArea,howManyTimes,httpDelete,httpPut,isArmstrongNumber,isSimilar,kmphToMph,levenshteinDistance,mphToKmph,pipeLog,quickSort,removeVowels,solveRPN,speechSynthesis,squareSum}