Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Last active June 5, 2024 17:39
Show Gist options
  • Save colelawrence/c6d0e719ad703f8b3d7f5ed42c0c50ab to your computer and use it in GitHub Desktop.
Save colelawrence/c6d0e719ad703f8b3d7f5ed42c0c50ab to your computer and use it in GitHub Desktop.
Record mapping as a map function (e.g. `[P in keyof T]: Transform<T[P]>`)
export function objMap<T extends Record<string, any>, U>(
template: T,
eachKey: <P extends Extract<keyof T, string>>(name: P, value: T[P]) => U,
): {
[P in Extract<keyof T, string>]: U;
} {
// @ts-ignore
return Object.fromEntries(
Object.entries(template)
.filter(([name]) => typeof name === "string")
.map(([name, value]) => {
// @ts-ignore
return [name, eachKey(name, value)];
}),
);
}
export function objMapWithProxy<T extends Record<string, any>, U>(
template: T,
eachKey: <P extends Extract<keyof T, string>>(name: P, value: T[P]) => U,
): {
[P in keyof T]: U;
} {
return new Proxy(template, {
get(target, prop, receiver) {
type P = Extract<keyof T, string>;
if (typeof prop === "string") {
return eachKey(prop as P, Reflect.get(target, prop, receiver) as T[P]);
}
return undefined;
},
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment