Skip to content

Commit

Permalink
feat(kernel): add bound decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
fkleuver committed Oct 11, 2019
1 parent 620f3b6 commit ecae358
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
23 changes: 23 additions & 0 deletions packages/kernel/src/functions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,3 +313,26 @@ export function mergeDistinct<T>(

return arr3;
}

/**
* Decorator. (lazily) bind the method to the class instance on first call.
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export function bound<T extends Function>(target: Object, key: string | symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> {
return (function () {
let fn = descriptor.value;
let boundFn: T;

return {
configurable: descriptor.configurable,
enumerable: descriptor.enumerable,
get(): T {
if (boundFn === void 0) {
boundFn = fn!.bind(this);
fn = void 0;
}
return boundFn;
},
};
})();
}
1 change: 1 addition & 0 deletions packages/kernel/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,4 +104,5 @@ export {
mergeDistinct,
isNumberOrBigInt,
isStringOrDate,
bound,
} from './functions';

0 comments on commit ecae358

Please sign in to comment.