-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy patharrays.js
58 lines (49 loc) · 1.32 KB
/
arrays.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* This module is just meant to be a realistic code example,
* to use in demonstrating some common git patterns.
*
* It is a collection of array utilities I often end up rewriting.
*/
/**
* Returns a new array with the indexes as values, i.e. [0, 1, ...len]
*
* @param {number} len - the length of the new array
* @returns {number[]}
*/
const range = (len) => {
const blanks = Array(...Array(len));
return blanks.map((_, i) => i);
};
/**
* Creates a new 2D array split into evenly sized chunks
*
* @param {array} arr - the array to chunk
* @param {number} size - the size of each chunk
* @returns {array[]}
*/
const chunk = (arr, size) => {
const parentSize = Math.ceil(arr.length / size);
return range(parentSize).map((index) => {
const start = index * size;
const end = start + size;
return arr.slice(start, end);
});
};
/**
* Groups the items in an array into sub-arrays by grouping function output
*
* @param {array} arr - the array to group
* @param {function} groupingFn - outputs the key to group an item under
* @returns {Object<string, array>}
*/
const groupBy = (arr, groupingFn) => {
const grouped = {};
arr.forEach((item, i) => {
const key = groupingFn(item, i, arr);
if (!grouped[key]) {
grouped[key] = [];
}
grouped[key].push(item);
});
return grouped;
};