Skip to content

Commit

Permalink
Re-write asyncMap with asyncIter
Browse files Browse the repository at this point in the history
  • Loading branch information
ivan-tymoshenko committed Apr 19, 2019
1 parent 689bafa commit f477971
Showing 1 changed file with 6 additions and 51 deletions.
57 changes: 6 additions & 51 deletions lib/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,57 +52,12 @@ const asyncMap = (items, fn, options = {}, done) => {
options = DEFAULT_OPTIONS;
}

const len = items.length || items.size;
const name = items.constructor.name;
let result = done ? new items.constructor() : null;
const data = common.iter(items);

if (!len || result === null) {
if (done) done(null, result);
return;
}

const min = options.min || DEFAULT_OPTIONS.min;
const percent = options.percent || DEFAULT_OPTIONS.percent;

let begin;
let sum = 0;
let count = 0;

const ratio = percent / (1 - percent);

const countNumber = () => {
const loopTime = Date.now() - begin;
const itemTime = sum / count;
const necessaryNumber = (ratio * loopTime) / itemTime;
return Math.max(necessaryNumber, min);
};

const next = () => {
const itemsNumber = count ? countNumber() : min;
const iterMax = Math.min(len, itemsNumber + count);

begin = Date.now();
for (; count < iterMax; count++) {
const itemResult = fn(data.next().value, count);
if (done) {
if (name === 'String') result += itemResult;
else if (name === 'Array') result.push(itemResult);
else if (name === 'Set') result.add(itemResult);
else result.set(itemResult);
}
}
sum += Date.now() - begin;

if (count < len) {
begin = Date.now();
setTimeout(next, 0);
} else if (done) {
done(null, result);
}
};

next();
asyncIter(items)
.throttle(options.percent)
.map(fn)
.toArray()
.then(array => done(null, array))
.catch(err => done(err));
};

// Asynchronous filter (iterate parallel)
Expand Down

0 comments on commit f477971

Please sign in to comment.