trunk

说明

将源数组根据指定大小分片

源码

用法

trunk.test.ts
1
import { trunk } from "../../utility/array/trunk";
2
3
describe('trunk', () => {
4
test('trunk should return an empty array when receive an empty array', () => {
5
const received: number[] = [];
6
const expected = 0;
7
8
const result = trunk<number>(received);
9
10
expect(result.length).toBe(expected);
11
});
12
13
test('trunk should return the divided array by default size', () => {
14
const received: number[] = [1, 2, 3, 4, 5, 6, 7];
15
const expected = {
16
length: 7,
17
value: [[1], [2], [3], [4], [5], [6], [7]],
18
};
19
20
const result = trunk<number>(received);
21
22
for (const [i, v] of result.entries()) {
23
for (const [ii, vv] of v.entries()) {
24
expect(vv).toBe(expected.value[i][ii]);
25
}
26
expect(v.length).toBe(expected.value[i].length);
27
}
28
expect(result.length).toBe(expected.length);
29
});
30
31
test('trunk should return the divided array by customized size', () => {
32
const received: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
33
const expected = {
34
s2: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]],
35
s5: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]],
36
s7: [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10]],
37
s10: [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]],
38
};
39
40
const p2 = trunk<number>(received, 2);
41
const p5 = trunk<number>(received, 5);
42
const p7 = trunk<number>(received, 7);
43
const p10 = trunk<number>(received, 10);
44
45
for (const [i, v] of p2.entries()) {
46
for (const [ii, vv] of v.entries()) {
47
expect(vv).toBe(expected.s2[i][ii]);
48
}
49
expect(v.length).toBe(expected.s2[i].length);
50
}
51
52
for (const [i, v] of p5.entries()) {
53
for (const [ii, vv] of v.entries()) {
54
expect(vv).toBe(expected.s5[i][ii]);
55
}
56
expect(v.length).toBe(expected.s5[i].length);
57
}
58
59
for (const [i, v] of p7.entries()) {
60
for (const [ii, vv] of v.entries()) {
61
expect(vv).toBe(expected.s7[i][ii]);
62
}
63
expect(v.length).toBe(expected.s7[i].length);
64
}
65
66
for (const [i, v] of p10.entries()) {
67
for (const [ii, vv] of v.entries()) {
68
expect(vv).toBe(expected.s10[i][ii]);
69
}
70
expect(v.length).toBe(expected.s10[i].length);
71
}
72
});
73
});
Copied!
最近更新 1yr ago
复制链接