UNPKG

2.67 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.combine = exports.divide = exports.unique = exports.isFlatArray = exports.lastOf = exports.firstOf = exports.transpose = exports.indexOf = exports.mapObject = void 0;
4/**
5 * Calls a defined callback function on each key:value of a object,
6 * and returns a object contains the result.
7 */
8function mapObject(object, callbackfn) {
9 return Object.entries(object).reduce((obj, [key, value]) => {
10 obj[key] = callbackfn(value, key, object);
11 return obj;
12 }, {});
13}
14exports.mapObject = mapObject;
15function indexOf(array) {
16 return array.map((_, i) => i);
17}
18exports.indexOf = indexOf;
19/**
20 * @example [[1, 2, 3], ['a', 'b', 'c']] => [[1, 'a'], [2, 'b'], [3, 'c']]
21 */
22function transpose(matrix) {
23 const row = matrix.length;
24 const col = matrix[0].length;
25 // Note: new Array(col).fill(new Array(row)) is not ok!!!
26 // Because in this case it will fill new Array(col) with the same array: new Array(row).
27 const transposed = new Array(col).fill(0).map(() => new Array(row));
28 for (let i = 0; i < col; i++) {
29 for (let j = 0; j < row; j++) {
30 transposed[i][j] = matrix[j][i];
31 }
32 }
33 return transposed;
34}
35exports.transpose = transpose;
36function firstOf(array) {
37 return array[0];
38}
39exports.firstOf = firstOf;
40function lastOf(array) {
41 return array[array.length - 1];
42}
43exports.lastOf = lastOf;
44function isFlatArray(array) {
45 return !array.some(Array.isArray);
46}
47exports.isFlatArray = isFlatArray;
48function unique(array) {
49 return Array.from(new Set(array));
50}
51exports.unique = unique;
52function divide(array, callbackfn) {
53 const result = [[], []];
54 array.forEach((item) => {
55 result[callbackfn(item) ? 0 : 1].push(item);
56 });
57 return result;
58}
59exports.divide = divide;
60function comb(array, len = array.length) {
61 if (len === 1)
62 return array.map((item) => [item]);
63 const result = [];
64 for (let i = 0; i < array.length; i++) {
65 const rest = array.slice(i + 1);
66 const restComb = comb(rest, len - 1);
67 restComb.forEach((comb) => {
68 result.push([array[i], ...comb]);
69 });
70 }
71 return result;
72}
73/**
74 * get all combinations of two elements in an array
75 * @example [1, 2, 3] => [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
76 * @param array
77 * @returns
78 */
79function combine(array) {
80 if (array.length === 1)
81 return [array];
82 const result = [];
83 for (let i = 1; i <= array.length; i++) {
84 result.push(...comb(array, i));
85 }
86 return result;
87}
88exports.combine = combine;
89//# sourceMappingURL=array.js.map
\No newline at end of file