Skip to content

Instantly share code, notes, and snippets.

@xnuk
Last active December 23, 2019 11:22
Show Gist options
  • Save xnuk/0ed1a8f570c814d36a1a5d3fcd8e53cb to your computer and use it in GitHub Desktop.
Save xnuk/0ed1a8f570c814d36a1a5d3fcd8e53cb to your computer and use it in GitHub Desktop.
const mapValues = <R, T extends { [key in K]: any }, K extends string = string>(
hash: T,
func: (value: T extends { [key in K]: infer V } ? V : never, key: K) => R
): { [key in K]: Exclude<R, undefined> } =>
(Object.keys(hash) as K[]).reduce((result, key) => {
const value = func(hash[key], key)
if (value !== undefined) {
result[key] = value as Exclude<R, undefined>
}
return result
}, {} as { [key in K]: Exclude<R, undefined> })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment