a = [1, 2, 3, 6, 9]; sum = eval(a.join`+`); console.log(sum); // outputs 21
Lately doing stuff with eval has been pretty fun. This does:
eval('1+2+3+6+9');
I used a more dynamic version of this recently:
const f = (o, ...a) => eval(a.join(o));
I had an idea for parsing Polish notation (+ 10 10)
by just transforming s-expressions like that into function calls: f('+', 10, 10)
... I've always liked Polish notation...
Here is the little Polish notation thing (warning extremely hacky)
const f = (o, ...a) => eval(a.join(o)); const polish = eq => eval( eq.replace(/\s+/g, ' ') .replace(/(\))\s([0-9])/g, '$1,$2') .replace(/([0-9]+)[^\)]/g, '$1,') .replace(/\(\s?([\+\-\*\\/])/g, 'f(`$1`,') ); console.log(polish('(* 2 2)')); console.log(polish('(* 2 2 (+ 3 2 1))')); console.log(polish('(- 10 3)')); console.log(polish('(/ (+ 10 10 (* 2 2)) 3)'));
See more stuff like this over @ Snippet Zone
Top comments (0)