DEV Community

Zevan Rosser
Zevan Rosser

Posted on

2 1

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay