-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserialize.js
More file actions
60 lines (52 loc) · 1.34 KB
/
serialize.js
File metadata and controls
60 lines (52 loc) · 1.34 KB
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
// serialise to Redis Serialisation Protocol (RESP) messages.
class Serializer {
constructor(request) {
this.input = request;
this.output = "";
this.stack = [];
}
serialize() {
this.analyseType(this.input);
while (this.stack.length > 0) {
const topArray = this.stack[this.stack.length - 1];
if (topArray.length > 0) {
this.analyseType(topArray.shift());
} else {
this.stack.pop();
}
}
return this.output;
}
analyseType(input) {
if (Array.isArray(input)) {
this.serializerArray(input);
} else if (typeof input === "string") {
this.serializeString(input);
} else if (!isNaN(input) && typeof input === "number") {
this.serializeInteger(input);
} else if (input === null) {
this.serializeNull();
} else if (input instanceof Error) {
this.serializerError(input);
} else {
throw new Error("Invalid input");
}
}
serializerArray(input) {
this.output += `*${input.length}\r\n`;
this.stack.push(input);
}
serializeString(input) {
this.output += `$${input.length}\r\n${input}\r\n`;
}
serializeInteger(input) {
this.output += `:${input}\r\n`;
}
serializeNull() {
this.output += "$-1\r\n";
}
serializerError(input) {
this.output += `-${input.message}\r\n`;
}
}
module.exports = Serializer;