Skip to content

Instantly share code, notes, and snippets.

@misebox
Last active April 9, 2024 17:12
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 misebox/91711c871fc8482a77419d742dd9989f to your computer and use it in GitHub Desktop.
Save misebox/91711c871fc8482a77419d742dd9989f to your computer and use it in GitHub Desktop.
TypeScript array utilities
/**
* オブジェクトの配列を辞書化
*/
const indexBy = <T, K extends T[keyof T] & (string | number | symbol)>(arr: T[], getKey: ((t: T) => K)): Record<K, T> => {
return arr.reduce((acc, cur) => {
const key = getKey(cur);
acc[key] = cur;
return acc;
}, {} as Record<K, T>);
};
/**
* リッチインターフェースのオブジェクトをコンテキストにバインドして、関数に分解できるようにする
*/
const bindMethodsToContext = <T extends Record<string, (...args: any[]) => any>>(api: T): T => (
Object.fromEntries(
Object.entries(api).map(([key, value]) => {
return [key, (...args: Parameters<typeof value>) => (value.bind(api)(...args))]
})
) as T
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment