Created
February 24, 2017 02:03
-
-
Save bobisme/ad9c82fdbff10015a104a5e464c04155 to your computer and use it in GitHub Desktop.
Extending Array.prototype with "parallel" mappers and reducers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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