-
Notifications
You must be signed in to change notification settings - Fork 0
/
lisp.test.mjs
97 lines (71 loc) · 2.4 KB
/
lisp.test.mjs
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { test } from 'tap'
import { exec } from './lisp.mjs'
test('should evaluate basic expressions correctly', (t) => {
t.plan(4)
exec({ '+': (a, b) => a + b }, ['+', 1, 2])
.then((result) => t.equal(result, 3, '1 + 2 = 3'))
exec({ '-': (a, b) => a - b }, ['-', 5, 3])
.then((result) => t.equal(result, 2, '5 - 3 = 2'))
exec({ '*': (a, b) => a * b }, ['*', 4, 3])
.then((result) => t.equal(result, 12, '4 * 3 = 12'))
exec({ '/': (a, b) => a / b }, ['/', 10, 2])
.then((result) => t.equal(result, 5, '10 / 2 = 5'))
})
test('should be able to call a partially applied function', async t => {
const env = {
'+': a => b => a + b
}
t.equal(typeof (await exec(env, ['+', 1])), 'function')
t.equal(await exec(env, [['+', 1], 2]), 3)
t.end()
})
test('should handle let expressions', (t) => {
t.plan(1)
exec({ '+': (a, b) => a + b }, ['let', [['x', 2], ['y', 3]], ['+', ['x'], ['y']]])
.then((result) => t.equal(result, 5, 'x + y = 5'))
})
test('should handle fn expressions', (t) => {
t.plan(2)
exec({}, ['fn', ['+', 1, 'x']])
.then((result) => t.equal(typeof result, 'function', 'should return a function'))
exec({ '+': (a, b) => a + b }, ['fn', ['+', 1, ['x']]])
.then(async (result) => {
t.equal(await result({ x: 2 }), 3, '1 + 2 = 3')
})
})
test('should throw an error for unknown expressions', (t) => {
t.plan(1)
exec({ '+': (a, b) => a + b }, ['-', 1, 2])
.catch((err) => t.equal(err.message, 'Unknown expression: -', 'should throw an error for unknown expressions'))
})
test('should evaluate nested expressions correctly', (t) => {
t.plan(1)
const env = {
'+': (a, b) => a + b,
'*': (a, b) => a * b
}
exec(env, ['*', 2, ['+', 1, 2]])
.then((result) => t.equal(result, 6, '2 * (1 + 2) = 6'))
})
test('should concatenate two arrays', async t => {
t.plan(1)
const env = {
array: (...args) => args,
concat: (a, b) => a.concat(b)
}
const expression = ['concat', ['array', 1, 2, 3], ['array', 4, 5, 6]]
const result = await exec(env, expression)
t.same(result, [1, 2, 3, 4, 5, 6])
})
test('should fetch the reference to the item on the env', async t => {
const value = 'yey'
const env = {
thing: () => value
}
const expression = ['ref', 'thing']
const result = await exec(env, expression)
t.same(result(), value)
const result2 = await exec(env, ['thing'])
t.same(result2, value)
t.end()
})