UNPKG

2.97 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3function conform(t) {
4 if (typeof t === 'undefined') {
5 return [];
6 }
7 if (!Array.isArray(t)) {
8 return [t];
9 }
10 return t;
11}
12exports.conform = conform;
13async function concurrentFilter(array, callback) {
14 const mapper = async (v) => [v, await callback(v)];
15 const mapped = await Promise.all(array.map(mapper));
16 return mapped
17 .filter(([, f]) => f)
18 .map(([v]) => v);
19}
20exports.concurrentFilter = concurrentFilter;
21async function filter(array, callback) {
22 const initial = [];
23 return reduce(array, async (acc, v, i, arr) => {
24 if (await callback(v, i, arr)) {
25 acc.push(v);
26 }
27 return acc;
28 }, initial);
29}
30exports.filter = filter;
31async function map(array, callback) {
32 const initial = [];
33 return reduce(array, async (acc, v, i, arr) => {
34 acc.push(await callback(v, i, arr));
35 return acc;
36 }, initial);
37}
38exports.map = map;
39async function reduce(array, callback, initialValue) {
40 const hadInitialValue = typeof initialValue === 'undefined';
41 const startingIndex = hadInitialValue ? 1 : 0;
42 if (typeof initialValue === 'undefined') {
43 if (array.length === 0) {
44 throw new TypeError('Reduce of empty array with no initial value');
45 }
46 initialValue = array[0];
47 }
48 let value = initialValue;
49 for (let i = startingIndex; i < array.length; i++) {
50 const v = await callback(value, array[i], i, array);
51 value = v;
52 }
53 return value;
54}
55exports.reduce = reduce;
56/**
57 * Splice an array.
58 *
59 * This function will return a new array with the standard splice behavior
60 * applied. Unlike the standard array splice, the array of removed items is not
61 * returned.
62 */
63function splice(array, start, deleteCount = array.length - start, ...items) {
64 const result = [...array];
65 result.splice(start, deleteCount, ...items);
66 return result;
67}
68exports.splice = splice;
69/**
70 * Move an item in an array by index.
71 *
72 * This function will return a new array with the item in the `fromIndex`
73 * position moved to the `toIndex` position. If `fromIndex` or `toIndex` are
74 * out of bounds, the array items remain unmoved.
75 */
76function move(array, fromIndex, toIndex) {
77 const element = array[fromIndex];
78 if (fromIndex < 0 || toIndex < 0 || fromIndex >= array.length || toIndex >= array.length) {
79 return [...array];
80 }
81 return splice(splice(array, fromIndex, 1), toIndex, 0, element);
82}
83exports.move = move;
84/**
85 * Replace an item in an array by index.
86 *
87 * This function will return a new array with the item in the `index` position
88 * replaced with `item`. If `index` is out of bounds, the item is not replaced.
89 */
90function replace(array, index, item) {
91 if (index < 0 || index > array.length) {
92 return [...array];
93 }
94 return splice(array, index, 1, item);
95}
96exports.replace = replace;