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 missing index to mapper function in pMapIterable #71

Merged
merged 1 commit into from
Apr 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ export function pMapIterable(
const promises = [];
let runningMappersCount = 0;
let isDone = false;
let index = 0;

function trySpawn() {
if (isDone || !(runningMappersCount < concurrency && promises.length < backpressure)) {
Expand All @@ -212,7 +213,7 @@ export function pMapIterable(
trySpawn();

try {
const returnValue = await mapper(await value);
const returnValue = await mapper(await value, index++);

runningMappersCount--;

Expand Down
25 changes: 25 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,16 @@ const mapper = async ([value, ms]) => {
return value;
};

const mapperWithIndex = async ([value, ms], index) => {
await delay(ms);

if (typeof value === 'function') {
value = await value();
}

return {value, index};
};

class ThrowingIterator {
constructor(max, throwOnIndex) {
this._max = max;
Expand Down Expand Up @@ -516,6 +526,21 @@ test('pMapIterable', async t => {
t.deepEqual(await collectAsyncIterable(pMapIterable(sharedInput, mapper)), [10, 20, 30]);
});

test('pMapIterable - index in mapper', async t => {
t.deepEqual(await collectAsyncIterable(pMapIterable(sharedInput, mapperWithIndex)), [
{value: 10, index: 0},
{value: 20, index: 1},
{value: 30, index: 2},
]);
t.deepEqual(await collectAsyncIterable(pMapIterable(longerSharedInput, mapperWithIndex)), [
{value: 10, index: 0},
{value: 20, index: 1},
{value: 30, index: 2},
{value: 40, index: 3},
{value: 50, index: 4},
]);
});

test('pMapIterable - empty', async t => {
t.deepEqual(await collectAsyncIterable(pMapIterable([], mapper)), []);
});
Expand Down