es-toolkit
Version:
A state-of-the-art, high-performance JavaScript utility library with a small bundle size and strong type annotations.
33 lines (32 loc) • 1.35 kB
JavaScript
import { limitAsync } from "../promise/limitAsync.mjs";
//#region src/object/mapValuesAsync.ts
/**
* Creates a new object with the same keys as the given object, but with values generated
* by running each own enumerable property of the object through the async iteratee function.
*
* @template T - The type of the object.
* @template K - The type of the keys in the object.
* @template V - The type of the new values generated by the async iteratee function.
*
* @param {T} object - The object to iterate over.
* @param {(value: T[K], key: K, object: T) => Promise<V>} getNewValue - The async function invoked per own enumerable property.
* @param {MapValuesAsyncOptions} [options] Optional configuration object.
* @returns {Promise<Record<K, V>>} - A promise that resolves to the new mapped object.
*
* @example
* // Example usage:
* const obj = { a: 1, b: 2 };
* const result = await mapValuesAsync(obj, async (value) => value * 2);
* console.log(result); // { a: 2, b: 4 }
*/
async function mapValuesAsync(object, getNewValue, options) {
const result = {};
const keys = Object.keys(object);
if (options?.concurrency) getNewValue = limitAsync(getNewValue, options.concurrency);
await Promise.all(keys.map(async (key) => {
result[key] = await getNewValue(object[key], key, object);
}));
return result;
}
//#endregion
export { mapValuesAsync };