UNPKG

surrogate

Version:

Object method hooks made easy

53 lines 2.12 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MethodIdentifier = void 0; const helpers_1 = require("../helpers"); class MethodIdentifier { constructor(instance) { this.instance = instance; } doesNotIncludeEvent(event, methods) { return !this.doesIncludeEvent(event) || !this.matchEvent(event, methods); } doesIncludeEvent(event) { return this.instanceMethodNames().includes(event); } matchEvent(event, methods) { return methods .filter((v) => v) .map((method) => new RegExp(method)) .some((regex) => regex.test(event)); } getApplicableMethods(event, methods) { const methodTest = new RegExp(event); return methods.includes(event) ? [event] : methods.filter((method) => methodTest.test(method)); } instanceMethodNames() { const prototype = Reflect.getPrototypeOf(this.instance) || {}; const properties = this.getPropertyNames(); return properties .filter((prop) => prop !== 'constructor') .filter((name) => this.isNotProperty(name)) .filter((name) => this.isNotAccessor(name, prototype)); } isNotProperty(name) { const descriptor = Reflect.getOwnPropertyDescriptor(this.instance, name); return (0, helpers_1.isUndefined)(descriptor); } isNotAccessor(name, prototype) { const descriptor = Reflect.getOwnPropertyDescriptor(prototype, name); return (0, helpers_1.isUndefined)(descriptor === null || descriptor === void 0 ? void 0 : descriptor.get) && (0, helpers_1.isUndefined)(descriptor === null || descriptor === void 0 ? void 0 : descriptor.set); } getPropertyNames() { const props = []; let current = this.instance; do { props.push(Object.getOwnPropertyNames(current)); } while ((current = Reflect.getPrototypeOf(current))); return [...new Set(props.flat()).values()]; } } exports.MethodIdentifier = MethodIdentifier; //# sourceMappingURL=index.js.map