meows
Version:
A kittybin of tools.
93 lines (92 loc) • 3.29 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const types_1 = require("./types");
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// Arrays
/**
* Shallow filters out redundant members.
* @example
* uniques([0, 1, 2, 2, 3, 3]) // => [0, 1, 2, 3]
*/
function uniques(arr) {
if (!Array.isArray(arr))
throw new TypeError(`uniques() requires an array, but got: ${arr}.`);
return [...new Set(arr)];
}
exports.uniques = uniques;
/**
* Shallow checks for repeat members.
* @example
* has_repeat([1, 2, 3]) // => false
* has_repeat([1, 2, 1]) // => true
*/
function hasRepeat(arr) {
if (!Array.isArray(arr))
throw new TypeError(`hasRepeat() requires an array, but got: ${arr}.`);
return arr.length !== new Set(arr).size;
}
exports.hasRepeat = hasRepeat;
/**
* Choose random member in array.
* @example
* randChoose([1, 'a', null]) // => 1
* randChoose([1, 'a', null]) // => null
*/
function randChoose(arr) {
if (types_1.notEmpty.arr(arr))
throw new TypeError(`randChoose() requires a non-empty array, but got: ${arr}.`);
return arr[Math.trunc(Math.random() * arr.length)];
}
exports.randChoose = randChoose;
/**
* A function for quickly generating arrays populated by a range of integers,
* with an optional skip interval.
*
* @example
* range(3) // => [0, 1, 2, 3]
* range(-3) // => [0, -1, -2, -3]
* range(-2, 2) // => [-2, -1, 0, 1, 2]
* range(2, -2) // => [2, 1, 0, -1, -2]
* range(-10, 10, 5) // => [-10, -5, 0, 5, 10]
* range(10, -10, 5) // => [10, 5, 0, -5, -10]
*/
function range(p0, pf, skip) {
const direction = pf > p0 ? 1 : -1;
const beautify = x => x === 0 ? 0 : x;
switch (arguments.length) {
case 1: return Array.from({ length: Math.abs(p0) + 1 }, (_, i) => i * Math.sign(p0)).map(beautify);
case 2: return Array.from({ length: Math.abs(pf - p0) + 1 }, (_, i) => i * direction + p0).map(beautify);
case 3: return Array.from({ length: Math.abs(Math.abs(pf - p0) / Math.abs(skip) + 1) }, (_, i) => i * skip * direction + p0).map(beautify);
default: return [];
}
}
exports.range = range;
/**
* Uses `λ` to populate an array of `items` length.
*
* @example
* series(x => 0.5*x**2 + 0.5*x, 5) // => [0, 1, 3, 6, 10]
*/
function series(λ, items = 1) {
return Array.from({ length: items }, (_, v) => λ(v));
}
exports.series = series;
/**
* Returns a shallow copy of the last value of your array. The default behavior
* is to return `undefined` on an empty array while `throwOnEmpty` is set to
* `false`.
*
* @example
* last([3, 2, 1]) // => 1
* last([3, 2, [1, 0]]) // => [1, 0]
* last([null]) // => null
* last([]) // => undefined if throwOnEmpty is false (!)
*/
function last(arr, throwOnEmpty = false) {
if (!Array.isArray(arr))
throw new TypeError(`arr() requires an array, but got: ${arr}.`);
if (throwOnEmpty && arr.length === 0)
throw new RangeError(`arr() requires a non-empty array.`);
return arr.slice(-1)[0];
}
exports.last = last;