DEV Community

Zevan Rosser
Zevan Rosser

Posted on

Array Sum Golfed

a = [1, 2, 3, 6, 9];
sum = eval(a.join`+`);
console.log(sum);
// outputs 21
Enter fullscreen mode Exit fullscreen mode

Lately doing stuff with eval has been pretty fun. This does:

eval('1+2+3+6+9');
Enter fullscreen mode Exit fullscreen mode

I used a more dynamic version of this recently:

const f = (o, ...a) => eval(a.join(o));
Enter fullscreen mode Exit fullscreen mode

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)'));
Enter fullscreen mode Exit fullscreen mode

See more stuff like this over @ Snippet Zone

Discussion (0)