forked from kanaka/mal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprinter.ts
42 lines (41 loc) · 1.35 KB
/
printer.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
import { Node, MalType } from "./types";
export function prStr(v: MalType, printReadably = true): string {
switch (v.type) {
case Node.List:
return `(${v.list.map(v => prStr(v, printReadably)).join(" ")})`;
case Node.Vector:
return `[${v.list.map(v => prStr(v, printReadably)).join(" ")}]`;
case Node.HashMap:
let result = "{";
for (const [key, value] of v.entries()) {
if (result !== "{") {
result += " ";
}
result += `${prStr(key, printReadably)} ${prStr(value, printReadably)}`;
}
result += "}";
return result;
case Node.Number:
case Node.Symbol:
case Node.Boolean:
return `${v.v}`;
case Node.String:
if (printReadably) {
const str = v.v
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"')
.replace(/\n/g, "\\n");
return `"${str}"`;
} else {
return v.v;
}
case Node.Nil:
return "nil";
case Node.Keyword:
return `:${v.v}`;
case Node.Function:
return "#<function>";
case Node.Atom:
return `(atom ${prStr(v.v, printReadably)})`;
}
}