Skip to content

Commit

Permalink
Add missing index parameter to mapper function in pMapIterable (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
noamokman committed Apr 3, 2024
1 parent 34006c9 commit dc597e5
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
3 changes: 2 additions & 1 deletion index.js
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
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

0 comments on commit dc597e5

Please sign in to comment.