diff --git a/p-map-values/__tests__/index.ts b/p-map-values/__tests__/index.ts index 9484261f..39654dbe 100644 --- a/p-map-values/__tests__/index.ts +++ b/p-map-values/__tests__/index.ts @@ -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); +}) diff --git a/p-map-values/src/index.ts b/p-map-values/src/index.ts index 69dee185..78471606 100644 --- a/p-map-values/src/index.ts +++ b/p-map-values/src/index.ts @@ -3,8 +3,11 @@ export default async function pMapValue ): Promise> { const result: Record = {} as Record + 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) }) )