@augment-vir/common
Version:
A collection of augments, helpers types, functions, and classes for any JavaScript environment.
66 lines (65 loc) • 2.4 kB
JavaScript
import { ensureError, getObjectTypedKeys } from '@augment-vir/core';
/**
* Creates a new object with the same keys as the input object, but with values set to the result of
* `mapCallback` for each property. This is the same as {@link mapObjectValues} except that this
* preserves Promise values: it doesn't wrap them all in a single promise.
*
* @category Object
* @category Package : @augment-vir/common
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function mapObjectValuesSync(inputObject, mapCallback) {
const mappedObject = getObjectTypedKeys(inputObject).reduce((accum, currentKey) => {
const mappedValue = mapCallback(currentKey, inputObject[currentKey], inputObject);
accum[currentKey] = mappedValue;
return accum;
}, {});
return mappedObject;
}
/**
* Creates a new object with the same keys as the input object, but with values set to the result of
* `mapCallback` for each property. Automatically handles an async `mapCallback`.
*
* @category Object
* @category Package : @augment-vir/common
* @example
*
* ```ts
* import {mapObjectValues} from '@augment-vir/common';
*
* mapObjectValues({a: 1, b: 2}, (key, value) => {
* return `key-${key} value-${value}`;
* });
* // output is `{a: 'key-a value-1', b: 'key-b value-2'}`
* ```
*
* @package [`@augment-vir/common`](https://www.npmjs.com/package/@augment-vir/common)
*/
export function mapObjectValues(inputObject, mapCallback) {
let gotAPromise = false;
const mappedObject = getObjectTypedKeys(inputObject).reduce((accum, currentKey) => {
const mappedValue = mapCallback(currentKey, inputObject[currentKey], inputObject);
if (mappedValue instanceof Promise) {
gotAPromise = true;
}
accum[currentKey] = mappedValue;
return accum;
}, {});
if (gotAPromise) {
return new Promise(async (resolve, reject) => {
try {
await Promise.all(getObjectTypedKeys(mappedObject).map(async (key) => {
const value = await mappedObject[key];
mappedObject[key] = value;
}));
resolve(mappedObject);
}
catch (error) {
reject(ensureError(error));
}
});
}
else {
return mappedObject;
}
}