-
Notifications
You must be signed in to change notification settings - Fork 269
/
index.js
56 lines (43 loc) · 1.12 KB
/
index.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
const errFirstArgument = 'Invalid Argument: Expected an array as first argument';
const errSecondArguemnt = 'Invalid Argument: Expected a positive number as second argument';
function validateArguments(array, size) {
if (!Array.isArray(array)) {
throw new Error(errFirstArgument);
}
if (typeof size !== 'number' || size < 0) {
throw new Error(errSecondArguemnt);
}
if (size > array.length) {
return [array];
}
return 0;
}
function arrayChunk({ array, size }) {
validateArguments(array, size);
const result = [];
for (let i = 0; i < array.length; i += 1) {
const lastChunk = result[result.length - 1];
if (!lastChunk || lastChunk.length === size) {
result.push([array[i]]);
} else {
lastChunk.push(array[i]);
}
}
return result;
}
function chunkUsingSlice({ array, size }) {
validateArguments(array, size);
let index = 0;
const result = [];
while (index < array.length) {
result.push(array.slice(index, index + size));
index += size;
}
return result;
}
module.exports = {
errFirstArgument,
errSecondArguemnt,
arrayChunk,
chunkUsingSlice,
};