Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pMapIterable #63

Merged
merged 25 commits into from Dec 5, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
100 changes: 100 additions & 0 deletions index.js
@@ -1,4 +1,5 @@
import AggregateError from 'aggregate-error';
import createDeferredAsyncIterator from 'deferred-async-iterator';

/**
An error to be thrown when the request is aborted by AbortController.
Expand Down Expand Up @@ -194,4 +195,103 @@ export default async function pMap(
});
}

export function pMapIterable(
iterable,
mapper,
{
concurrency = Number.POSITIVE_INFINITY,
} = {},
) {
if (iterable[Symbol.iterator] === undefined && iterable[Symbol.asyncIterator] === undefined) {
throw new TypeError(`Expected \`input\` to be either an \`Iterable\` or \`AsyncIterable\`, got (${typeof iterable})`);
}

if (typeof mapper !== 'function') {
throw new TypeError('Mapper function is required');
}

if (!((Number.isSafeInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency >= 1)) {
throw new TypeError(`Expected \`concurrency\` to be an integer from 1 and up or \`Infinity\`, got \`${concurrency}\` (${typeof concurrency})`);
}

return {
[Symbol.asyncIterator]() {
Richienb marked this conversation as resolved.
Show resolved Hide resolved
const {next, nextError, complete, onCleanup, iterator} = createDeferredAsyncIterator();
Richienb marked this conversation as resolved.
Show resolved Hide resolved

const iterator_ = iterable[Symbol.iterator] === undefined ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();

let currentIndex = 0;
let isFlushing = false;
let isComplete = false;

(async () => {
await onCleanup;
isComplete = true;
})();

const valuePromises = [];

async function flushValues() {
if (isFlushing) {
return;
}

isFlushing = true;

for await (const promise of valuePromises) {
try {
const value = await promise;

if (value === pMapSkip) {
continue;
}

next(value);
} catch (error) {
nextError(error);
}
}

isFlushing = false;
}

async function nextItem() {
if (isComplete) {
return;
}

const {done, value} = await iterator_.next();

if (isComplete) {
return;
}

const index = currentIndex;
currentIndex++;

if (done) {
isComplete = true;
return;
}

valuePromises.push(mapper(value, index));
flushValues();

await nextItem();
}

(async () => {
for (let index = 0; index < concurrency; index++) {
// eslint-disable-next-line no-await-in-loop
await nextItem();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if nextItem throws? It will cause an unhandled rejection.

}

complete();
})();

return iterator;
},
Richienb marked this conversation as resolved.
Show resolved Hide resolved
};
}

export const pMapSkip = Symbol('skip');
3 changes: 2 additions & 1 deletion package.json
Expand Up @@ -41,7 +41,8 @@
"bluebird"
],
"dependencies": {
"aggregate-error": "^4.0.0"
"aggregate-error": "^4.0.0",
"deferred-async-iterator": "^3.0.0"
},
"devDependencies": {
"ava": "^4.1.0",
Expand Down
16 changes: 15 additions & 1 deletion test.js
Expand Up @@ -4,7 +4,7 @@ import inRange from 'in-range';
import timeSpan from 'time-span';
import randomInt from 'random-int';
import AggregateError from 'aggregate-error';
import pMap, {pMapSkip} from './index.js';
import pMap, {pMapIterable, pMapSkip} from './index.js';

const sharedInput = [
[async () => 10, 300],
Expand Down Expand Up @@ -486,3 +486,17 @@ if (globalThis.AbortController !== undefined) {
});
});
}

async function collectAsyncIterable(asyncIterable) {
const values = [];

for await (const value of asyncIterable) {
values.push(value);
}

return values;
}

test('pMapIterable', async t => {
t.deepEqual(await collectAsyncIterable(pMapIterable(sharedInput, mapper)), [10, 20, 30]);
});