Skip to content

Commit

Permalink
fix(p-map-values): Keep order of entries in pMapValue
Browse files Browse the repository at this point in the history
This method is used during the pack phase in pnpm.

As the key order is not guaranteed to be kept by it, the dependency order
may be changed as a result, leading to non-reproducible builds.

This fixes zkochan#208
  • Loading branch information
kisstkondoros committed Nov 25, 2024
1 parent 221d0b8 commit 639da5a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
19 changes: 19 additions & 0 deletions p-map-values/__tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,22 @@ import pMapValues from '../src'
test('pMapValues', async () => {
expect(await pMapValues(async (value: number) => value * 2, {a: 1, b: 2})).toEqual({a: 2, b: 4})
})

test('pMapValues - with simulated async work', async () => {
const delay = async (milliseconds: number) => {
return new Promise((resolve) => {
setTimeout(resolve, milliseconds)
});
}
const input = {a: 1, b: 2};

const mapped = await pMapValues(async (value: number) => {
await delay((2 - value) * 100);
return value * 2;
}, input);

const expected= {a: 2, b: 4};

expect(Object.keys(mapped)).toStrictEqual(Object.keys(expected));
expect(mapped).toStrictEqual(expected);
})
5 changes: 4 additions & 1 deletion p-map-values/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ export default async function pMapValue<K extends string | number | symbol, V, U
obj: Record<K, V>
): Promise<Record<K, U>> {
const result: Record<K, U> = {} as Record<K, U>
const entries = Object.entries(obj) as [K, V][];
await Promise.all(
Object.entries(obj).map(async ([key, value]: any) => { // eslint-disable-line @typescript-eslint/no-explicit-any
entries.map(async ([key, value]) => {
// initialize property in the resulting object to guarantee key order
result[key] = undefined as unknown as U;
result[key] = await mapper(value, key, obj)
})
)
Expand Down

0 comments on commit 639da5a

Please sign in to comment.