Created
July 10, 2017 20:17
-
-
Save eschwartz/c3b89bd8f4234af26478ea798c6e5ae0 to your computer and use it in GitHub Desktop.
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