csvan
csvan

Reputation: 9474

Applying a built-in JS operator

Say I want to add a sequence of numbers using reduce:

[1,2,3].reduce((all, current) => all + current, 0)

is there any built-in (I know I can write an auxiliary function that does this) way to pass the + operator as an applicable function? E.g.:

[1,2,3].reduce(+, 0)

I know the above isn't valid JS, but I hope it demonstrates what I want to achieve.

Upvotes: 0

Views: 49

Answers (4)

Mr_Green
Mr_Green

Reputation: 41842

This is for people who use Lodash.

You can use the available _.multiply, _.add, _.subtract and _.divide functions with Array.reduce.

Here is an example:

function calculate(operand, elements) {
    return _.first(elements.reduce((acc, cur) => _.chunk(acc.concat(cur), 2).map(c => _[operand].apply(null, c)), []));
}

// Then

calculate('add', [1,2,3,4,5]);   // 15

Upvotes: 0

Jonas Wilms
Jonas Wilms

Reputation: 138447

const op = k => {
  "+": (a,b) => a + b,
  "-": (a,b) => a - b,
  "/": (a,b) => a / b,
  "*": (a,b) => a * b
}[k];

So you can do:

[1,2,3].reduce(op("+"))

(The startvalue is not neccessary here)

Reduce could be wrapped in another function to shortify this even more:

const reduce = (arr, o,s) => arr.reduce(typeof o === " function" ? o : op(o), s);

So you can do:

reduce([1,2,3,4],"+");

Upvotes: 1

Nandu Kalidindi
Nandu Kalidindi

Reputation: 6280

There is no built in function like that.

This is totally a hack and will probably replace the native reduce functionality.

Array.prototype.reduce = function (operator, inital) {
  // Assuming operator is always = "+" 
  // You need to implement your versions for subtraction, multiplication etc may be using a switch case
  var sum = inital;
  this.forEach(elem => { sum += elem });
  return sum;
}

console.log([1, 2, 3, 4].reduce("+", 0))
// 10
console.log([1, 2, 3, 4].reduce("+", 10))
// 20

Upvotes: 1

Ingo Bürk
Ingo Bürk

Reputation: 20043

No, no such symbol exists. But you can just write it yourself as you pointed out:

const Operator = { plus: (a, b) => a+b };
//...reduce(Operator.plus, 0)

The answer to your question is simply: no.

Upvotes: 1

Related Questions