Skip to content

Instantly share code, notes, and snippets.

@NV
Created January 30, 2010 23:27
Show Gist options
  • Save NV/290781 to your computer and use it in GitHub Desktop.
Save NV/290781 to your computer and use it in GitHub Desktop.
String argument for Array reduce function
var A_reduce = [].reduce;
Array.prototype.reduce = function reduce (callback, initialValue) {
var operator = callback;
return typeof operator == 'string' && /^[ +*/%-><!&|^?,.]/.test(operator)
? eval(this.join(operator))
: A_reduce.apply(this, arguments)
};
[1,2,3,4].reduce('+') // 10
[1,2,3,4].reduce('*') // 24
[2, 0, 1].reduce('&&') // 0
[2, 0, 1].reduce('||') // 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment