UNPKG

deca-method-lister

Version:

A utility to extract and list all methods from JavaScript objects, including inherited methods from the prototype chain

39 lines (38 loc) 1.44 kB
/** * Extracts and returns all method names from a JavaScript object, including inherited methods from the prototype chain. * * This function traverses the entire prototype chain of the given object using Object.getPrototypeOf() * and collects all property names using Object.getOwnPropertyNames(). It then filters the results * to include only properties that are functions (methods). * * @param {Object} obj - The object to extract methods from * @returns {string[]} An array of method names (strings) available on the object * * @example * // Simple object with custom methods * const myObject = { * name: 'John', * greet() { return `Hello, I'm ${this.name}`; }, * getInfo() { return this.name; } * }; * * const methods = getMethods(myObject); * console.log(methods); // ['greet', 'getInfo', 'constructor', 'hasOwnProperty', 'toString', ...] * * @example * // Built-in JavaScript objects * const arr = []; * const arrayMethods = getMethods(arr); * console.log(arrayMethods); // ['push', 'pop', 'slice', 'splice', 'map', 'filter', ...] */ const getMethods = (obj) => { let properties = new Set() let currentObj = obj do { Object.getOwnPropertyNames(currentObj).map(item => properties.add(item)) } while ((currentObj = Object.getPrototypeOf(currentObj))) return [...properties.keys()].filter(item => typeof obj[item] === 'function') } module.exports = { getMethods }