Yotam Salmon Yotam Salmon -5 years ago 93
Javascript Question

Variable containing an operator in Javascript

I'm trying to make a change to a variable using a custom operator (I will explain it clearlier now).

I have an array of numbers, and I have to

it. First 2 numbers will be added, then in the second reducing they will be substracted, then multiplied, divided and exponentiated. Basically:

[1,2,3,4,5] -> 0
0/5=0 -> 0

So I saw an implementation like this:

f => f.reduce((a,b,c) => [a + b, a - b, a * b, a / b, a ** b][c % 5])

And wondered, can I make an array of operators in some way, and implement it like this?

f => f.reduce((a,b,c) => a [+,-,*,/,**][c%5] b)

Clearly this syntax is incorrect, but in the terms of an idea, does something like this exist?

Answer Source

You can use eval() method

var f = [1, 2, 3, 4, 5];

  f.reduce((a, b, c) => eval(a + ['+', '-', '*', '/'][c-1] + b))

Also I don't prefer to use eval(), refer : Don't use eval needlessly!

UPDATE : Also as @NinaScholz said, you can reduce the code by using string instead of string array. Both string and array have same effect in this case.

var f = [1, 2, 3, 4, 5];

  f.reduce((a, b, c) => eval(a + '+-*/'[c - 1] + b))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download