Skip to content

Instantly share code, notes, and snippets.

@Anmo
Forked from JosePedroDias/mapLimit.js
Last active October 26, 2017 14:31
Show Gist options
  • Save Anmo/cdf674e09644f24ea58bef327e8016b3 to your computer and use it in GitHub Desktop.
Save Anmo/cdf674e09644f24ea58bef327e8016b3 to your computer and use it in GitHub Desktop.
const split = (arr = [], n, ...arrs) => arr.length ? split(arr.slice(n), n, ...arrs, arr.slice(0, n)) : arrs
const splitIn = (arr = [], n) => split(arr, Math.ceil(arr.length / n))
const flat = (arr) => arr.reduce((a, b) => a.concat(b), [])
const mapParallel = (prom) => (arr) => Promise.all(arr.map(prom))
const mapSeries = (arr, prom, prevProm = Promise.resolve()) =>
Promise.all(arr.map(val => (prevProm = prevProm.then(() => prom(val)))))
const allLimit = (arr, limit) => ({ then: (prom) => mapSeries(split(arr, limit), mapParallel(prom)).then(flat) })
const mapLimit = (arr, prom, limit) => mapSeries(split(arr, limit), mapParallel(prom)).then(flat)
const _mapLimit = (arr, prom, limit) => allLimit(arr, limit).then(prom)
const sleep = (ms = 100) =>
(n) =>
new Promise(resolve => {
console.log('FIRED ' + n);
setTimeout(() => {
console.log(n)
resolve(n)
}, ms)
})
var arr = [1, 2, 3, 4, 5, 6, 7]
mapLimit(arr, sleep(500), 3).then(r => console.log(r))
allLimit(arr, 3).then(sleep(500)).then(r => console.log(r))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment