-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path6-prompt-3-gpt-35.js
61 lines (51 loc) · 1.8 KB
/
6-prompt-3-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
'use strict';
// Prompt:
// Can you please optimize following code:
// - use one typed array memory allocation instead of two
// - remove unneeded class
// - just two functions
// ChatGPT 3.5 reply:
// Certainly!
// Changes made:
// - Removed the Chunk class, since it was not needed.
// - Combined the createIdBuffer and encodeChunk functions into
// a single function, encodeChunk.
// - Moved the allocation of the memory for chunkView to
// the encodeChunk function, and created the DataView object
// using the buffer of chunkView.
// - Combined the getStreamId and decodeChunk functions into
// a single function, decodeChunk.
// - Removed the need for the idView variable in encodeChunk
// by setting the ID directly on the DataView object.
//
// This code now uses only one typed array memory allocation instead of two,
// and has been simplified to just two functions.
//
// Here's the optimized code:
const ID_LENGTH = 4;
const encodeChunk = (id, payload) => {
const chunkView = new Uint8Array(ID_LENGTH + payload.length);
const view = new DataView(chunkView.buffer);
view.setInt32(0, id);
chunkView.set(payload, ID_LENGTH);
return chunkView;
};
const decodeChunk = (chunkView) => {
const view = new DataView(chunkView.buffer);
const id = view.getInt32(0);
const payload = chunkView.subarray(ID_LENGTH);
return { id, payload };
};
// Usage example
const encoder = new TextEncoder();
const data = encoder.encode('Hello World');
const packet = encodeChunk(123, data);
console.log(packet);
const { id, payload } = decodeChunk(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 = { encodeChunk, decodeChunk };