Skip to content

Instantly share code, notes, and snippets.

@bobisme
Created February 24, 2017 02:03
Show Gist options
  • Save bobisme/ad9c82fdbff10015a104a5e464c04155 to your computer and use it in GitHub Desktop.
Save bobisme/ad9c82fdbff10015a104a5e464c04155 to your computer and use it in GitHub Desktop.
Extending Array.prototype with "parallel" mappers and reducers.
Array.prototype.paraMap = function(...fns) {
return fns.map(fn => this.map(fn))
}
Array.prototype.paraReduce = function(...fns) {
let reduceArgs
let init = fns[fns.length - 1]
if (typeof init !== 'function') {
reduceArgs = fns.slice(0, -1).map(fn => [fn, init])
} else {
reduceArgs = fns.map(fn => [fn])
}
return reduceArgs.map(args => Array.prototype.reduce.apply(this, args))
}
console.log([1, 2, 3].paraMap(
(x => x % 3),
(x => x * x),
(x => -x)
))
// [ [ 1, 2, 0 ], [ 1, 4, 9 ], [ -1, -2, -3 ] ]
console.log([1, 2, 3].paraReduce(
((a, b) => a > b ? a : b), // max
((a, b) => a < b ? a : b) // min
))
// [ 3, 1 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment