Last active
April 9, 2024 17:12
-
-
Save misebox/91711c871fc8482a77419d742dd9989f to your computer and use it in GitHub Desktop.
TypeScript array utilities
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
/** | |
* オブジェクトの配列を辞書化 | |
*/ | |
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