Like _.mapValues, but asynchronous
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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