/
chunksOf.ts
50 lines (44 loc) 路 1.45 KB
/
chunksOf.ts
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
import { compose } from "../compose.ts";
import { concatUint8Array } from "../../../tools/concatUint8Array.ts";
/** Output Uint8Array of fixed size*/
export const chunksOf = (byteLength: number) => {
return compose<
Uint8Array,
{
currByteLength: number;
chunks: Uint8Array[];
rest: Uint8Array | undefined
},
Uint8Array
>(
[
(chunk_, prev) => {
const [chunk, previousByteLength, chunks] =
prev.rest !== undefined ?
[concatUint8Array([chunk_, prev.rest]), 0, []]
:
[chunk_, prev.currByteLength, prev.chunks]
;
const currByteLength = previousByteLength + chunk.byteLength;
return [
{
currByteLength,
"chunks": [...chunks, chunk],
"rest": currByteLength >= byteLength ?
chunk.slice(byteLength - currByteLength)
:
undefined
}
];
},
{
"currByteLength": 0,
"chunks": [],
"rest": undefined
}
],
({ rest, chunks }) => rest !== undefined ?
[concatUint8Array(chunks, byteLength)] :
null
)
};