-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathindex.js
80 lines (73 loc) · 1.55 KB
/
index.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// @ts-check
/**
* Build pair
* @example
* const pair = cons(5, 'hello');
* @example
* const pair = cons(cons(1, null), 'world');
*/
export const cons = (a, b) => {
const pair = (message) => {
switch (message) {
case 'car':
return a;
case 'cdr':
return b;
default:
throw new Error(`Unknown message '${message}'`);
}
};
pair.pair = true;
return pair;
};
/**
* Check if something is pair
* @example
* const pair = cons(5, 'hello');
* isPair(pair); // true
* isPair(5); // false
*/
export const isPair = (pair) => typeof pair === 'function' && pair.pair;
export const checkPair = (pair) => {
if (!isPair(pair)) {
const value = typeof pair === 'object' ? JSON.stringify(pair, null, 2) : String(pair);
throw new Error(`Argument must be pair, but it was '${value}'`);
}
};
/**
* Get car (first element) from pair
* @example
* const pair = cons(5, 'hello');
* car(pair); // 5
*/
export const car = (pair) => {
checkPair(pair);
return pair('car');
};
/**
* Get cdr (second element) from pair
* @example
* const pair = cons(5, 'hello');
* cdr(pair); // hello
*/
export const cdr = (pair) => {
checkPair(pair);
return pair('cdr');
};
/**
* Convert pair to string (recursively)
* @example
* toString(cons('', 10)); // ('', 10)
*/
export const toString = (pair) => {
checkPair(pair);
const rec = (p) => {
if (!isPair(p)) {
return String(p);
}
const left = car(p);
const right = cdr(p);
return `(${rec(left)}, ${rec(right)})`;
};
return rec(pair);
};