-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2-prompt-1-gpt-35.js
65 lines (53 loc) · 1.94 KB
/
2-prompt-1-gpt-35.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
59
60
61
62
63
64
65
'use strict';
// Prompt:
// Optimize following code for complexity, readability, memory, and speed
// ChatGPT 3.5 reply:
// The code looks reasonably efficient, readable, and concise. However, there
// are a few minor optimizations that can be made:
// - Use a constant instead of ID_LENGTH in Chunk.encode().
// This will make the code more readable and slightly faster since
// the interpreter doesn't have to look up the constant.
// - Use DataView's byteLength property instead of payload.length to calculate
// the length of the chunkView. This avoids having to pass ID_LENGTH around
// and makes the code more concise.
// - Use Int32Array instead of DataView in createIdBuffer() and getStreamId().
// This will make the code faster since Int32Array is optimized for 32-bit
// integer operations.
const ID_BYTE_LENGTH = 4;
const createIdBuffer = (id) => {
const buffer = new ArrayBuffer(ID_BYTE_LENGTH);
const view = new Int32Array(buffer);
view[0] = id;
return buffer;
};
const getStreamId = (buffer) => {
const view = new Int32Array(buffer);
return view[0];
};
class Chunk {
static encode(id, payload) {
const idView = new Uint8Array(createIdBuffer(id));
const chunkView = new Uint8Array(idView.byteLength + payload.byteLength);
chunkView.set(idView);
chunkView.set(payload, idView.byteLength);
return chunkView;
}
static decode(chunkView) {
const id = getStreamId(chunkView.buffer);
const payload = chunkView.subarray(ID_BYTE_LENGTH);
return { id, payload };
}
}
// Usage example
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 };