Last active
October 2, 2023 17:42
-
-
Save matthew-dean/9267ab91b0c701cfb956f7f0c1549b55 to your computer and use it in GitHub Desktop.
Getting all methods of an object - TypeScript version
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
type Obj = Record<any, any> | |
const isGetter = (x: Obj, name: string) => Boolean((Object.getOwnPropertyDescriptor(x, name) ?? {})?.get) | |
const isFunction = (x: Obj, name: string) => typeof x[name] === 'function' | |
const deepFunctions = (x: Obj): string[] => | |
(x && x !== Object.prototype && | |
Object.getOwnPropertyNames(x) | |
.filter(name => isGetter(x, name) || isFunction(x, name)) | |
.concat(deepFunctions(Object.getPrototypeOf(x)) || [])) || [] | |
const distinctDeepFunctions = (x: Obj) => Array.from(new Set(deepFunctions(x))) | |
const getMethods = (obj: Obj) => distinctDeepFunctions(obj).filter( | |
name => name !== 'constructor' && !~name.indexOf('__')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment