UNPKG

deca-method-lister

Version:

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

256 lines (188 loc) • 6.57 kB
# deca-method-lister A lightweight utility to extract and list all methods from JavaScript objects, including inherited methods from the prototype chain. Now with CLI support for analyzing JavaScript files! ## Installation ```bash npm install deca-method-lister ``` ## Usage ### Programmatic Usage ```javascript const { getMethods } = require('deca-method-lister'); // Example with a simple object const myObject = { name: 'John', age: 30, greet() { return `Hello, I'm ${this.name}`; }, getAge() { return this.age; } }; const methods = getMethods(myObject); console.log(methods); // Output: ['greet', 'getAge', 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'valueOf', 'toLocaleString'] ``` ### CLI Usage Analyze JavaScript files and generate method documentation: ```bash # Analyze a JavaScript file npx deca-method-lister myfile.js # Specify output file (default: methods.js) npx deca-method-lister myfile.js output.js ``` **Example CLI Output:** ```bash $ npx deca-method-lister index.js āœ… Successfully analyzed index.js šŸ“„ Found 1 methods šŸ’¾ Generated methods.js šŸ“‹ Methods found: 1. getMethods (line 27) └─ Extracts and returns all method names from a JavaScript object, including inherited methods from the prototype chain. ``` **Generated File Structure:** ```javascript // Auto-generated method information for index.js // Generated on 2024-01-15T10:30:00.000Z const methods = [ { "name": "getMethods", "description": "Extracts and returns all method names from a JavaScript object, including inherited methods from the prototype chain.", "parameters": [ { "type": "Object", "name": "obj", "description": "The object to extract methods from" } ], "returnType": "string[]", "file": "index.js", "line": 27 } ]; module.exports = { methods, count: methods.length, file: 'index.js', generatedAt: '2024-01-15T10:30:00.000Z' }; ``` ## Examples ### Built-in Objects ```javascript const { getMethods } = require('deca-method-lister'); // Array methods const arr = []; const arrayMethods = getMethods(arr); console.log(arrayMethods); // Output: ['push', 'pop', 'shift', 'unshift', 'slice', 'splice', 'concat', 'join', 'reverse', 'sort', 'filter', 'map', 'reduce', 'forEach', ...] // String methods const str = "hello"; const stringMethods = getMethods(str); console.log(stringMethods); // Output: ['charAt', 'charCodeAt', 'concat', 'indexOf', 'lastIndexOf', 'slice', 'substring', 'substr', 'toLowerCase', 'toUpperCase', ...] // Date methods const date = new Date(); const dateMethods = getMethods(date); console.log(dateMethods); // Output: ['getTime', 'getFullYear', 'getMonth', 'getDate', 'getHours', 'getMinutes', 'getSeconds', 'setTime', 'setFullYear', ...] ``` ### Custom Classes ```javascript const { getMethods } = require('deca-method-lister'); class Animal { constructor(name) { this.name = name; } speak() { return `${this.name} makes a sound`; } move() { return `${this.name} moves`; } } class Dog extends Animal { constructor(name, breed) { super(name); this.breed = breed; } bark() { return `${this.name} barks`; } fetch() { return `${this.name} fetches the ball`; } } const dog = new Dog('Buddy', 'Golden Retriever'); const dogMethods = getMethods(dog); console.log(dogMethods); // Output: ['bark', 'fetch', 'speak', 'move', 'constructor', 'hasOwnProperty', 'isPrototypeOf', ...] ``` ### Filtering Results ```javascript const { getMethods } = require('deca-method-lister'); const myObject = { customMethod1() { return 'one'; }, customMethod2() { return 'two'; } }; const allMethods = getMethods(myObject); const customMethods = allMethods.filter(method => !['constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'valueOf', 'toLocaleString'].includes(method) ); console.log(customMethods); // Output: ['customMethod1', 'customMethod2'] ``` ## API ### `getMethods(obj)` Returns an array of all method names (functions) available on the given object, including inherited methods from the prototype chain. #### Parameters - `obj` (Object): The object to extract methods from #### Returns - `Array<string>`: An array of method names #### Example ```javascript const { getMethods } = require('deca-method-lister'); const methods = getMethods(someObject); console.log(methods); // ['method1', 'method2', 'inheritedMethod', ...] ``` ## CLI Features The CLI tool analyzes JavaScript files and extracts: - **Method names** and their locations (line numbers) - **JSDoc documentation** including descriptions, parameters, and return types - **Function signatures** with parameter names - **Method metadata** including file information and timestamps ### Supported Method Patterns - Function declarations: `function methodName() {}` - Arrow functions: `const methodName = () => {}` - Object method shorthand: `methodName() {}` - Class methods: `methodName() {}` - Async methods: `async methodName() {}` ### JSDoc Support The CLI automatically extracts JSDoc comments and parses: - Method descriptions - `@param` tags with types and descriptions - `@returns` tags with return types - Method parameters from function signatures ## How it Works The `getMethods` 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). This approach ensures that: - All own methods are included - All inherited methods from the prototype chain are included - Only functions are returned (properties with other types are filtered out) - Duplicate method names are automatically handled by using a `Set` ## Use Cases - **API Documentation**: Automatically generate documentation for object methods - **Code Analysis**: Analyze JavaScript files to understand their structure - **Testing**: Ensure all expected methods are available on objects - **Debugging**: Quickly inspect what methods are available on an object - **Introspection**: Build tools that need to understand object capabilities - **Educational**: Learn about JavaScript's prototype chain and inheritance ## License MIT ## Author Tom Tarpey ## Contributing Contributions are welcome! Please feel free to submit a Pull Request. ## Repository [GitHub Repository](https://github.com/decagondev/deca-method-lister)