Skip to content

Commit

Permalink
fix: conserve fn.length and fn.name (#79)
Browse files Browse the repository at this point in the history
  • Loading branch information
bertho-zero committed Apr 11, 2021
1 parent 38b44c3 commit d9bc9af
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/hooks/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { compose, Middleware } from './compose';
import {
HookContext, setManager, HookContextData, HookOptions, convertOptions, setMiddleware
} from './base';
import { copyProperties } from './utils';
import { copyFnProperties, copyProperties } from './utils';

export function getOriginal (fn: any): any {
return typeof fn.original === 'function' ? getOriginal(fn.original) : fn;
Expand Down Expand Up @@ -51,6 +51,7 @@ export function functionHooks <F> (fn: F, managerOrMiddleware: HookOptions) {
return compose(hookChain).call(this, context);
};

copyFnProperties(wrapper, fn);
copyProperties(wrapper, fn);
setManager(wrapper, manager);

Expand Down
16 changes: 16 additions & 0 deletions packages/hooks/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,19 @@ export function copyProperties <F> (target: F, ...originals: any[]) {

return target;
}

export function copyFnProperties <F> (target: F, original : any) {
const internalProps = ['name', 'length'];

try {
for (const prop of internalProps) {
const value = original[prop];

Object.defineProperty(target, prop, { value });
}
} catch (e) {
// Avoid IE error
}

return target;
}
7 changes: 7 additions & 0 deletions packages/hooks/test/function.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ describe('functionHooks', () => {
assert.ok(getManager(fn) !== null);
});

it('conserve name and length properties', () => {
const fn = hooks(hello, []);

assert.strictEqual(fn.length, hello.length);
assert.strictEqual(fn.name, hello.name);
});

it('throws an error with non function', () => {
assert.throws(() => functionHooks({}, middleware([])));
})
Expand Down

0 comments on commit d9bc9af

Please sign in to comment.