Travis build: 1012
This commit is contained in:
37
README.md
37
README.md
@@ -669,14 +669,13 @@ const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Pr
|
|||||||
<summary>Examples</summary>
|
<summary>Examples</summary>
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|
||||||
const sum = pipeAsyncFunctions(
|
const sum = pipeAsyncFunctions(
|
||||||
x => x + 1,
|
x => x + 1,
|
||||||
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
|
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
|
||||||
x => x + 3,
|
x => x + 3,
|
||||||
async x => (await x) + 4
|
async x => (await x) + 4
|
||||||
);
|
);
|
||||||
(async() => {
|
(async () => {
|
||||||
console.log(await sum(5)); // 15 (after one second)
|
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`).
|
The `func` is invoked with three arguments (`value, index, array`).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|
||||||
const remove = (arr, func) =>
|
const remove = (arr, func) =>
|
||||||
Array.isArray(arr)
|
Array.isArray(arr)
|
||||||
? arr.filter(func).reduce((acc, val) => {
|
? arr.filter(func).reduce((acc, val) => {
|
||||||
arr.splice(arr.indexOf(val), 1);
|
arr.splice(arr.indexOf(val), 1);
|
||||||
return acc.concat(val);
|
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.
|
Throws an exception if `n` is a negative number.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|
||||||
const factorial = n =>
|
const factorial = n =>
|
||||||
n < 0
|
n < 0
|
||||||
? (() => {
|
? (() => {
|
||||||
throw new TypeError('Negative numbers are not allowed!');
|
throw new TypeError('Negative numbers are not allowed!');
|
||||||
})()
|
})()
|
||||||
: n <= 1
|
: n <= 1
|
||||||
? 1
|
? 1
|
||||||
: n * factorial(n - 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`.
|
Returns `num` mapped between `outMin`-`outMax` from `inMin`-`inMax`.
|
||||||
|
|
||||||
```js
|
```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>
|
<details>
|
||||||
<summary>Examples</summary>
|
<summary>Examples</summary>
|
||||||
|
|
||||||
```js
|
```js
|
||||||
mapNumRange(5,0,10,0,100); // 50
|
|
||||||
|
mapNumRange(5, 0, 10, 0, 100); // 50
|
||||||
```
|
```
|
||||||
|
|
||||||
</details>
|
</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`.
|
Use `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|
||||||
const deepMapKeys = (obj, f) =>
|
const deepMapKeys = (obj, f) =>
|
||||||
Array.isArray(obj)
|
Array.isArray(obj)
|
||||||
? obj.map(val => deepMapKeys(val, f))
|
? obj.map(val => deepMapKeys(val, f))
|
||||||
: typeof obj === 'object'
|
: 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)] =
|
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;
|
: 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.
|
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
|
```js
|
||||||
|
|
||||||
const dig = (obj, target) =>
|
const dig = (obj, target) =>
|
||||||
target in obj
|
target in obj
|
||||||
? obj[target]
|
? obj[target]
|
||||||
: Object.values(obj).reduce((acc, val) => {
|
: Object.values(obj).reduce((acc, val) => {
|
||||||
if (acc !== undefined) return acc;
|
if (acc !== undefined) return acc;
|
||||||
if (typeof val === 'object') return dig(val, target);
|
if (typeof val === 'object') return dig(val, target);
|
||||||
}, undefined);
|
}, undefined);
|
||||||
```
|
```
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
|
|||||||
@@ -339,6 +339,7 @@
|
|||||||
<li><a tags="math,beginner,intermediate" href="./math#isprime">isPrime</a></li>
|
<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,recursion,beginner" href="./math#lcm">lcm</a></li>
|
||||||
<li><a tags="math,utility,advanced" href="./math#luhncheck">luhnCheck</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,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,intermediate" href="./math#median">median</a></li>
|
||||||
<li><a tags="math,array,beginner" href="./math#midpoint">midpoint</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
@@ -339,6 +339,7 @@
|
|||||||
<li><a tags="math,beginner,intermediate" href="./math#isprime">isPrime</a></li>
|
<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,recursion,beginner" href="./math#lcm">lcm</a></li>
|
||||||
<li><a tags="math,utility,advanced" href="./math#luhncheck">luhnCheck</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,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,intermediate" href="./math#median">median</a></li>
|
||||||
<li><a tags="math,array,beginner" href="./math#midpoint">midpoint</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
@@ -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`.
|
Use `Array.prototype.reduce()` to create a new object with the same values and mapped keys using `fn`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|
||||||
const deepMapKeys = (obj, f) =>
|
const deepMapKeys = (obj, f) =>
|
||||||
Array.isArray(obj)
|
Array.isArray(obj)
|
||||||
? obj.map(val => deepMapKeys(val, f))
|
? obj.map(val => deepMapKeys(val, f))
|
||||||
: typeof obj === 'object'
|
: 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)] =
|
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;
|
: obj;
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
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
|
```js
|
||||||
|
|
||||||
const dig = (obj, target) =>
|
const dig = (obj, target) =>
|
||||||
target in obj
|
target in obj
|
||||||
? obj[target]
|
? obj[target]
|
||||||
: Object.values(obj).reduce((acc, val) => {
|
: Object.values(obj).reduce((acc, val) => {
|
||||||
if (acc !== undefined) return acc;
|
if (acc !== undefined) return acc;
|
||||||
if (typeof val === 'object') return dig(val, target);
|
if (typeof val === 'object') return dig(val, target);
|
||||||
}, undefined);
|
}, undefined);
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|||||||
@@ -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.
|
Throws an exception if `n` is a negative number.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|
||||||
const factorial = n =>
|
const factorial = n =>
|
||||||
n < 0
|
n < 0
|
||||||
? (() => {
|
? (() => {
|
||||||
throw new TypeError('Negative numbers are not allowed!');
|
throw new TypeError('Negative numbers are not allowed!');
|
||||||
})()
|
})()
|
||||||
: n <= 1
|
: n <= 1
|
||||||
? 1
|
? 1
|
||||||
: n * factorial(n - 1);
|
: n * factorial(n - 1);
|
||||||
|
|||||||
@@ -5,9 +5,11 @@ Maps a number from one range to another range.
|
|||||||
Returns `num` mapped between `outMin`-`outMax` from `inMin`-`inMax`.
|
Returns `num` mapped between `outMin`-`outMax` from `inMin`-`inMax`.
|
||||||
|
|
||||||
```js
|
```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
|
```js
|
||||||
mapNumRange(5,0,10,0,100); // 50
|
|
||||||
|
mapNumRange(5, 0, 10, 0, 100); // 50
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -11,14 +11,13 @@ const pipeAsyncFunctions = (...fns) => arg => fns.reduce((p, f) => p.then(f), Pr
|
|||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|
||||||
const sum = pipeAsyncFunctions(
|
const sum = pipeAsyncFunctions(
|
||||||
x => x + 1,
|
x => x + 1,
|
||||||
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
|
x => new Promise(resolve => setTimeout(() => resolve(x + 2), 1000)),
|
||||||
x => x + 3,
|
x => x + 3,
|
||||||
async x => (await x) + 4
|
async x => (await x) + 4
|
||||||
);
|
);
|
||||||
(async() => {
|
(async () => {
|
||||||
console.log(await sum(5)); // 15 (after one second)
|
console.log(await sum(5)); // 15 (after one second)
|
||||||
})();
|
})();
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -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`).
|
The `func` is invoked with three arguments (`value, index, array`).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
|
|
||||||
const remove = (arr, func) =>
|
const remove = (arr, func) =>
|
||||||
Array.isArray(arr)
|
Array.isArray(arr)
|
||||||
? arr.filter(func).reduce((acc, val) => {
|
? arr.filter(func).reduce((acc, val) => {
|
||||||
arr.splice(arr.indexOf(val), 1);
|
arr.splice(arr.indexOf(val), 1);
|
||||||
return acc.concat(val);
|
return acc.concat(val);
|
||||||
}, [])
|
}, [])
|
||||||
: [];
|
: [];
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
249
test/_30s.js
249
test/_30s.js
@@ -1,6 +1,53 @@
|
|||||||
const fs = typeof require !== "undefined" && require('fs');
|
const fs = typeof require !== "undefined" && require('fs');
|
||||||
const crypto = typeof require !== "undefined" && require('crypto');
|
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 all = (arr, fn = Boolean) => arr.every(fn);
|
||||||
const allEqual = arr => arr.every(val => val === arr[0]);
|
const allEqual = arr => arr.every(val => val === arr[0]);
|
||||||
const any = (arr, fn = Boolean) => arr.some(fn);
|
const any = (arr, fn = Boolean) => arr.some(fn);
|
||||||
@@ -124,6 +171,7 @@ const countBy = (arr, fn) =>
|
|||||||
acc[val] = (acc[val] || 0) + 1;
|
acc[val] = (acc[val] || 0) + 1;
|
||||||
return acc;
|
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) => {
|
const counter = (selector, start, end, step = 1, duration = 2000) => {
|
||||||
let current = start,
|
let current = start,
|
||||||
_step = (end - start) * step < 0 ? -step : step,
|
_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))));
|
}, Math.abs(Math.floor(duration / (end - start))));
|
||||||
return timer;
|
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 createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
|
||||||
const createElement = str => {
|
const createElement = str => {
|
||||||
@@ -157,21 +204,6 @@ const createEventHub = () => ({
|
|||||||
if (i > -1) this.hub[event].splice(i, 1);
|
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 currentURL = () => window.location.href;
|
||||||
const curry = (fn, arity = fn.length, ...args) =>
|
const curry = (fn, arity = fn.length, ...args) =>
|
||||||
arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
|
arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
|
||||||
@@ -203,17 +235,16 @@ const deepFreeze = obj =>
|
|||||||
prop =>
|
prop =>
|
||||||
!(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])
|
!(obj[prop] instanceof Object) || Object.isFrozen(obj[prop]) ? null : deepFreeze(obj[prop])
|
||||||
) || Object.freeze(obj);
|
) || Object.freeze(obj);
|
||||||
|
|
||||||
const deepMapKeys = (obj, f) =>
|
const deepMapKeys = (obj, f) =>
|
||||||
Array.isArray(obj)
|
Array.isArray(obj)
|
||||||
? obj.map(val => deepMapKeys(val, f))
|
? obj.map(val => deepMapKeys(val, f))
|
||||||
: typeof obj === 'object'
|
: typeof obj === 'object'
|
||||||
? Object.keys(obj).reduce((acc, current) => {
|
? 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);
|
||||||
val !== null && typeof val === 'object' ? deepMapKeys(val, f) : (acc[f(current)] = val);
|
return acc;
|
||||||
return acc;
|
}, {})
|
||||||
: obj;
|
: obj;
|
||||||
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
|
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
|
||||||
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
|
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)));
|
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 differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
|
|
||||||
const dig = (obj, target) =>
|
const dig = (obj, target) =>
|
||||||
target in obj
|
target in obj
|
||||||
? obj[target]
|
? obj[target]
|
||||||
: Object.values(obj).reduce((acc, val) => {
|
: Object.values(obj).reduce((acc, val) => {
|
||||||
? obj[target]
|
if (acc !== undefined) return acc;
|
||||||
: Object.values(obj).reduce((acc, val) => {
|
if (typeof val === 'object') return dig(val, target);
|
||||||
if (acc !== undefined) return acc;
|
}, undefined);
|
||||||
const digitize = n => [...`${n}`].map(i => parseInt(i));
|
const digitize = n => [...`${n}`].map(i => parseInt(i));
|
||||||
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
|
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
|
||||||
const drop = (arr, n = 1) => arr.slice(n);
|
const drop = (arr, n = 1) => arr.slice(n);
|
||||||
@@ -308,12 +338,11 @@ const extendHex = shortHex =>
|
|||||||
.split('')
|
.split('')
|
||||||
.map(x => x + x)
|
.map(x => x + x)
|
||||||
.join('');
|
.join('');
|
||||||
.map(x => x + x)
|
|
||||||
const factorial = n =>
|
const factorial = n =>
|
||||||
n < 0
|
n < 0
|
||||||
? (() => {
|
? (() => {
|
||||||
const factorial = n =>
|
throw new TypeError('Negative numbers are not allowed!');
|
||||||
n < 0
|
})()
|
||||||
: n <= 1
|
: n <= 1
|
||||||
? 1
|
? 1
|
||||||
: n * factorial(n - 1);
|
: n * factorial(n - 1);
|
||||||
@@ -352,6 +381,11 @@ const forEachRight = (arr, callback) =>
|
|||||||
.slice(0)
|
.slice(0)
|
||||||
.reverse()
|
.reverse()
|
||||||
.forEach(callback);
|
.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 => {
|
const formatDuration = ms => {
|
||||||
if (ms < 0) ms = -ms;
|
if (ms < 0) ms = -ms;
|
||||||
const time = {
|
const time = {
|
||||||
@@ -366,11 +400,6 @@ const formatDuration = ms => {
|
|||||||
.map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
|
.map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
|
||||||
.join(', ');
|
.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 = '_') =>
|
const fromCamelCase = (str, separator = '_') =>
|
||||||
str
|
str
|
||||||
.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
|
.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
|
||||||
@@ -500,6 +529,10 @@ const hz = (fn, iterations = 100) => {
|
|||||||
for (let i = 0; i < iterations; i++) fn();
|
for (let i = 0; i < iterations; i++) fn();
|
||||||
return (1000 * iterations) / (performance.now() - before);
|
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 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 indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);
|
||||||
const initial = arr => arr.slice(0, -1);
|
const initial = arr => arr.slice(0, -1);
|
||||||
@@ -516,10 +549,6 @@ const initializeNDArray = (val, ...args) =>
|
|||||||
args.length === 0
|
args.length === 0
|
||||||
? val
|
? val
|
||||||
: Array.from({ length: args[0] }).map(() => initializeNDArray(val, ...args.slice(1)));
|
: 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 insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);
|
||||||
const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);
|
const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);
|
||||||
const intersection = (a, b) => {
|
const intersection = (a, b) => {
|
||||||
@@ -631,19 +660,6 @@ const join = (arr, separator = ',', end = separator) =>
|
|||||||
: acc + val + 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 last = arr => arr[arr.length - 1];
|
||||||
const lcm = (...arr) => {
|
const lcm = (...arr) => {
|
||||||
const gcd = (x, y) => (!y ? x : gcd(y, x % y));
|
const gcd = (x, y) => (!y ? x : gcd(y, x % y));
|
||||||
@@ -671,7 +687,8 @@ const mapKeys = (obj, fn) =>
|
|||||||
acc[fn(obj[k], k, obj)] = obj[k];
|
acc[fn(obj[k], k, obj)] = obj[k];
|
||||||
return acc;
|
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) =>
|
const mapObject = (arr, fn) =>
|
||||||
(a => (
|
(a => (
|
||||||
(a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
|
(a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
|
||||||
@@ -777,14 +794,6 @@ const on = (el, evt, fn, opts = {}) => {
|
|||||||
el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false);
|
el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false);
|
||||||
if (opts.target) return delegatorFn;
|
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 => {
|
const onUserInputChange = callback => {
|
||||||
let type = 'mouse',
|
let type = 'mouse',
|
||||||
lastTime = 0;
|
lastTime = 0;
|
||||||
@@ -799,6 +808,14 @@ const onUserInputChange = callback => {
|
|||||||
(type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler);
|
(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) =>
|
const orderBy = (arr, props, orders) =>
|
||||||
[...arr].sort((a, b) =>
|
[...arr].sort((a, b) =>
|
||||||
props.reduce((acc, prop, i) => {
|
props.reduce((acc, prop, i) => {
|
||||||
@@ -853,7 +870,7 @@ const pickBy = (obj, fn) =>
|
|||||||
Object.keys(obj)
|
Object.keys(obj)
|
||||||
.filter(k => fn(obj[k], k))
|
.filter(k => fn(obj[k], k))
|
||||||
.reduce((acc, key) => ((acc[key] = obj[key]), acc), {});
|
.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 pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
|
||||||
const pluralize = (val, word, plural = word + 's') => {
|
const pluralize = (val, word, plural = word + 's') => {
|
||||||
const _pluralize = (num, 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) =>
|
const redirect = (url, asLink = true) =>
|
||||||
asLink ? (window.location.href = url) : window.location.replace(url);
|
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) =>
|
const reducedFilter = (data, keys, fn) =>
|
||||||
data.filter(fn).map(el =>
|
data.filter(fn).map(el =>
|
||||||
keys.reduce((acc, key) => {
|
keys.reduce((acc, key) => {
|
||||||
@@ -965,18 +986,13 @@ const reducedFilter = (data, keys, fn) =>
|
|||||||
return acc;
|
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 reject = (pred, array) => array.filter((...args) => !pred(...args));
|
||||||
);
|
|
||||||
const remove = (arr, func) =>
|
const remove = (arr, func) =>
|
||||||
Array.isArray(arr)
|
Array.isArray(arr)
|
||||||
? arr.filter(func).reduce((acc, val) => {
|
? arr.filter(func).reduce((acc, val) => {
|
||||||
arr.reduce((a, b) => (comparator(a, b) >= 0 ? b : a));
|
arr.splice(arr.indexOf(val), 1);
|
||||||
const reject = (pred, array) => array.filter((...args) => !pred(...args));
|
return acc.concat(val);
|
||||||
|
}, [])
|
||||||
: [];
|
: [];
|
||||||
const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');
|
const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');
|
||||||
const renameKeys = (keysMap, obj) =>
|
const renameKeys = (keysMap, obj) =>
|
||||||
@@ -988,7 +1004,6 @@ const renameKeys = (keysMap, obj) =>
|
|||||||
{}
|
{}
|
||||||
);
|
);
|
||||||
const reverseString = str => [...str].reverse().join('');
|
const reverseString = str => [...str].reverse().join('');
|
||||||
(acc, key) => ({
|
|
||||||
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
|
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
|
||||||
const runAsync = fn => {
|
const runAsync = fn => {
|
||||||
const worker = new Worker(
|
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 => {
|
const timeTaken = callback => {
|
||||||
console.time('timeTaken');
|
console.time('timeTaken');
|
||||||
const r = callback();
|
const r = callback();
|
||||||
console.timeEnd('timeTaken');
|
console.timeEnd('timeTaken');
|
||||||
return r;
|
return r;
|
||||||
};
|
};
|
||||||
|
const times = (n, fn, context = undefined) => {
|
||||||
|
let i = 0;
|
||||||
|
while (fn.call(context, i) !== false && ++i < n) {}
|
||||||
|
};
|
||||||
const toCamelCase = str => {
|
const toCamelCase = str => {
|
||||||
let s =
|
let s =
|
||||||
str &&
|
str &&
|
||||||
@@ -1185,7 +1200,6 @@ const toCamelCase = str => {
|
|||||||
const toCurrency = (n, curr, LanguageFormat = undefined) =>
|
const toCurrency = (n, curr, LanguageFormat = undefined) =>
|
||||||
Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
|
Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
|
||||||
const toDecimalMark = num => num.toLocaleString('en-US');
|
const toDecimalMark = num => num.toLocaleString('en-US');
|
||||||
.map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
|
|
||||||
const toHash = (object, key) =>
|
const toHash = (object, key) =>
|
||||||
Array.prototype.reduce.call(
|
Array.prototype.reduce.call(
|
||||||
object,
|
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)
|
.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())
|
.map(x => x.toLowerCase())
|
||||||
.join('-');
|
.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 toOrdinalSuffix = num => {
|
||||||
const int = parseInt(num),
|
const int = parseInt(num),
|
||||||
digits = [int % 10, int % 100],
|
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)
|
.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))
|
.map(x => x.charAt(0).toUpperCase() + x.slice(1))
|
||||||
.join(' ');
|
.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 transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc);
|
||||||
const triggerEvent = (el, eventType, detail) =>
|
const triggerEvent = (el, eventType, detail) =>
|
||||||
el.dispatchEvent(new CustomEvent(eventType, { detail }));
|
el.dispatchEvent(new CustomEvent(eventType, { detail }));
|
||||||
@@ -1310,24 +1325,6 @@ const unzipWith = (arr, fn) =>
|
|||||||
}).map(x => [])
|
}).map(x => [])
|
||||||
)
|
)
|
||||||
.map(val => fn(...val));
|
.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 validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
|
||||||
const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x);
|
const when = (pred, whenTrue) => x => (pred(x) ? whenTrue(x) : x);
|
||||||
const without = (arr, ...args) => arr.filter(v => !args.includes(v));
|
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]))
|
(_, 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;
|
if (start > end) return -1;
|
||||||
const mid = Math.floor((start + end) / 2);
|
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, start, mid - 1);
|
||||||
if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);
|
if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);
|
||||||
return mid;
|
return mid;
|
||||||
};
|
};
|
||||||
|
const celsiusToFahrenheit = degrees => 1.8 * degrees + 32;
|
||||||
const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
|
const cleanObj = (obj, keysToKeep = [], childIndicator) => {
|
||||||
Object.keys(obj).forEach(key => {
|
Object.keys(obj).forEach(key => {
|
||||||
if (key === childIndicator) {
|
if (key === childIndicator) {
|
||||||
cleanObj(obj[key], keysToKeep, childIndicator);
|
cleanObj(obj[key], keysToKeep, childIndicator);
|
||||||
@@ -1368,9 +1369,9 @@ const zipWith = (...array) => {
|
|||||||
});
|
});
|
||||||
return obj;
|
return obj;
|
||||||
};
|
};
|
||||||
const cleanObj = (obj, keysToKeep = [], childIndicator) => {
|
const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);
|
||||||
Object.keys(obj).forEach(key => {
|
const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
|
||||||
if (key === childIndicator) {
|
const factors = (num, primes = false) => {
|
||||||
const isPrime = num => {
|
const isPrime = num => {
|
||||||
const boundary = Math.floor(Math.sqrt(num));
|
const boundary = Math.floor(Math.sqrt(num));
|
||||||
for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
|
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;
|
return primes ? array.filter(isPrime) : array;
|
||||||
};
|
};
|
||||||
const isNeg = num < 0;
|
const fahrenheitToCelsius = degrees => (degrees - 32) * 5/9;
|
||||||
num = isNeg ? -num : num;
|
const fibonacciCountUntilNum = num =>
|
||||||
Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
|
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));
|
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(
|
return Array.from({ length: n }).reduce(
|
||||||
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
|
(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
|
const p = (side_a + side_b + side_c) / 2
|
||||||
return Math.sqrt(p * (p-side_a) * (p-side_b) * (p-side_c))
|
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 === 1 || divisor === -1) return Infinity;
|
||||||
if (divisor === 0) return 0;
|
if (divisor === 0) return 0;
|
||||||
let i = 0;
|
let i = 0;
|
||||||
@@ -1413,14 +1414,14 @@ const zipWith = (...array) => {
|
|||||||
}
|
}
|
||||||
return i;
|
return i;
|
||||||
};
|
};
|
||||||
);
|
const httpDelete = (url, callback, err = console.error) => {
|
||||||
const request = new XMLHttpRequest();
|
const request = new XMLHttpRequest();
|
||||||
request.open('DELETE', url, true);
|
request.open('DELETE', url, true);
|
||||||
request.onload = () => callback(request);
|
request.onload = () => callback(request);
|
||||||
request.onerror = () => err(request);
|
request.onerror = () => err(request);
|
||||||
request.send();
|
request.send();
|
||||||
};
|
};
|
||||||
|
const httpPut = (url, data, callback, err = console.error) => {
|
||||||
const request = new XMLHttpRequest();
|
const request = new XMLHttpRequest();
|
||||||
request.open("PUT", url, true);
|
request.open("PUT", url, true);
|
||||||
request.setRequestHeader('Content-type','application/json; charset=utf-8');
|
request.setRequestHeader('Content-type','application/json; charset=utf-8');
|
||||||
@@ -1428,11 +1429,11 @@ const zipWith = (...array) => {
|
|||||||
request.onerror = () => err(request);
|
request.onerror = () => err(request);
|
||||||
request.send(data);
|
request.send(data);
|
||||||
};
|
};
|
||||||
}
|
const isArmstrongNumber = digits =>
|
||||||
(arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
|
(arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)(
|
||||||
(digits + '').split('')
|
(digits + '').split('')
|
||||||
);
|
);
|
||||||
const httpDelete = (url, callback, err = console.error) => {
|
const isSimilar = (pattern, str) =>
|
||||||
[...str].reduce(
|
[...str].reduce(
|
||||||
(matchIndex, char) =>
|
(matchIndex, char) =>
|
||||||
char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase()
|
char.toLowerCase() === (pattern[matchIndex] || '').toLowerCase()
|
||||||
@@ -1440,12 +1441,8 @@ const zipWith = (...array) => {
|
|||||||
: matchIndex,
|
: matchIndex,
|
||||||
0
|
0
|
||||||
) === pattern.length;
|
) === pattern.length;
|
||||||
const httpPut = (url, data, callback, err = console.error) => {
|
const kmphToMph = (kmph) => 0.621371192 * kmph;
|
||||||
const request = new XMLHttpRequest();
|
const levenshteinDistance = (string1, string2) => {
|
||||||
request.open("PUT", url, true);
|
|
||||||
request.setRequestHeader('Content-type','application/json; charset=utf-8');
|
|
||||||
request.onload = () => callback(request);
|
|
||||||
request.onerror = () => err(request);
|
|
||||||
if (string1.length === 0) return string2.length;
|
if (string1.length === 0) return string2.length;
|
||||||
if (string2.length === 0) return string1.length;
|
if (string2.length === 0) return string1.length;
|
||||||
let matrix = Array(string2.length + 1)
|
let matrix = Array(string2.length + 1)
|
||||||
@@ -1469,9 +1466,9 @@ const zipWith = (...array) => {
|
|||||||
}
|
}
|
||||||
return matrix[string2.length][string1.length];
|
return matrix[string2.length][string1.length];
|
||||||
};
|
};
|
||||||
|
const mphToKmph = (mph) => 1.6093440006146922 * mph;
|
||||||
const levenshteinDistance = (string1, string2) => {
|
const pipeLog = data => console.log(data) || data;
|
||||||
if (string1.length === 0) return string2.length;
|
const quickSort = ([n, ...nums], desc) =>
|
||||||
isNaN(n)
|
isNaN(n)
|
||||||
? []
|
? []
|
||||||
: [
|
: [
|
||||||
@@ -1479,8 +1476,8 @@ const zipWith = (...array) => {
|
|||||||
n,
|
n,
|
||||||
...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)
|
...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc)
|
||||||
];
|
];
|
||||||
for (let i = 1; i <= string2.length; i++) {
|
const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi, repl);
|
||||||
for (let j = 1; j <= string1.length; j++) {
|
const solveRPN = rpn => {
|
||||||
const OPERATORS = {
|
const OPERATORS = {
|
||||||
'*': (a, b) => a * b,
|
'*': (a, b) => a * b,
|
||||||
'+': (a, b) => a + b,
|
'+': (a, b) => a + b,
|
||||||
@@ -1508,12 +1505,12 @@ const zipWith = (...array) => {
|
|||||||
if (stack.length === 1) return stack.pop();
|
if (stack.length === 1) return stack.pop();
|
||||||
else throw `${rpn} is not a proper RPN. Please check it and try again`;
|
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);
|
const msg = new SpeechSynthesisUtterance(message);
|
||||||
msg.voice = window.speechSynthesis.getVoices()[0];
|
msg.voice = window.speechSynthesis.getVoices()[0];
|
||||||
window.speechSynthesis.speak(msg);
|
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}
|
||||||
Reference in New Issue
Block a user