Created
January 25, 2017 17:58
-
-
Save ox/5b0c5e66af512b66d23f62d1b5c6f748 to your computer and use it in GitHub Desktop.
Partitioned iterator
This file contains hidden or 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
const Promise = require('bluebird'); | |
function iterator(entities = [], mapFn, concurrent = 2) { | |
const partitionSize = entities.length / concurrent; | |
const partitions = []; | |
for (let i = 0; i < concurrent; i++) { | |
const start = i * partitionSize; | |
const entitiesInPartition = entities.slice(start, start + partitionSize); | |
partitions.push(Promise.mapSeries(entitiesInPartition, mapFn)); | |
} | |
return Promise.all(partitions); | |
} | |
const entities = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]; | |
const fn = (x) => x * x; | |
const concurrent = 2; | |
iterator(entities, fn, concurrent).then(console.log); | |
/* | |
[ | |
[ 1, 4, 9, 16, 25, 36, 49 ], | |
[ 64, 81, 100, 121, 144, 169, 196 ] | |
] | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment