Skip to content

Commit cf6aac0

Browse files
authored
Create 736-parse-lisp-expression.js
1 parent e589510 commit cf6aac0

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

736-parse-lisp-expression.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @param {string} expression
3+
* @return {number}
4+
*/
5+
const evaluate = (x) =>
6+
e(
7+
JSON.parse(
8+
x.replace(/[() ]|([a-z][a-z0-9]*)/g, (m) =>
9+
m == '(' ? '[' : m == ')' ? ']' : m == ' ' ? ',' : `"${m}"`
10+
)
11+
)
12+
)
13+
const e = (x, v = []) =>
14+
({
15+
string: () => v.find((y) => y[0] === x)[1],
16+
number: () => x,
17+
object: () =>
18+
({
19+
add: () => e(x[1], v) + e(x[2], v),
20+
mult: () => e(x[1], v) * e(x[2], v),
21+
let: () =>
22+
e(
23+
x[x.length - 1],
24+
x
25+
.slice(1, -1)
26+
.reduce(
27+
({ v, t }, z) =>
28+
t ? { v: [[t, e(z, v)], ...v] } : { v, t: z },
29+
{ v }
30+
).v
31+
),
32+
}[x[0]]()),
33+
}[typeof x]())

0 commit comments

Comments
 (0)