Skip to content

Instantly share code, notes, and snippets.

@eschwartz
Created July 10, 2017 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eschwartz/c3b89bd8f4234af26478ea798c6e5ae0 to your computer and use it in GitHub Desktop.
Save eschwartz/c3b89bd8f4234af26478ea798c6e5ae0 to your computer and use it in GitHub Desktop.
Like _.mapValues, but asynchronous
// https://gist.github.com/eschwartz/70a15f12e6ef90f377d5d51fba9c86d8
import mapAsync from './mapAsync';
interface Dict<TVal> {
[key: string]: TVal
}
async function mapValuesAsync<TVal, TRes>(obj:Dict<TVal>, iter:(val:TVal, key:string) => Promise<TRes>):Promise<Dict<TRes>> {
const keyResPairs:[string, TRes][] = await mapAsync<string, [string, TRes]>(Object.keys(obj),
async (key:string) => {
const res = await iter(obj[key], key);
return [key, res];
}
);
return keyResPairs.reduce((obj:Dict<TRes>, [key, res]:[string, TRes]) => ({
...obj,
[key]: res
}), {});
}
export default mapValuesAsync;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment