-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1-initial.js
51 lines (40 loc) · 1.17 KB
/
1-initial.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
'use strict';
// Initial code (before optimizations)
const ID_LENGTH = 4;
const createIdBuffer = (id) => {
const buffer = new ArrayBuffer(ID_LENGTH);
const view = new DataView(buffer);
view.setInt32(0, id);
return buffer;
};
const getStreamId = (buffer) => {
const view = new DataView(buffer);
return view.getInt32(0);
};
class Chunk {
static encode(id, payload) {
const idView = new Uint8Array(createIdBuffer(id));
const chunkView = new Uint8Array(ID_LENGTH + payload.length);
chunkView.set(idView);
chunkView.set(payload, ID_LENGTH);
return chunkView;
}
static decode(chunkView) {
const id = getStreamId(chunkView.buffer);
const payload = chunkView.subarray(ID_LENGTH);
return { id, payload };
}
}
// Usage
const encoder = new TextEncoder();
const data = encoder.encode('Hello World');
const packet = Chunk.encode(123, data);
console.log(packet);
const { id, payload } = Chunk.decode(packet);
const decoder = new TextDecoder();
const text = decoder.decode(payload);
console.log({ id, payload: text });
const assert = require('node:assert/strict');
assert.equal(id, 123);
assert.equal(text, 'Hello World');
module.exports = { Chunk };