Skip to content

Instantly share code, notes, and snippets.

@dotsonjb14
Last active September 16, 2018 16:05
Show Gist options
  • Save dotsonjb14/a29003783aa7dd472f3a7a1b533faf44 to your computer and use it in GitHub Desktop.
Save dotsonjb14/a29003783aa7dd472f3a7a1b533faf44 to your computer and use it in GitHub Desktop.
Typescript decorator for a once ran function
function once(target, propertyKey: string, descriptor: PropertyDescriptor) {
let old = descriptor.value;
let ran = false;
descriptor.value = function () {
if (!ran) {
ran = true;
old.call(this);
}
}
}
function memoize(target, propertyKey: string, descriptor: PropertyDescriptor) {
let old = descriptor.value;
let ran = false;
let val = null;
descriptor.value = function () {
if (!ran) {
ran = true;
val = old.call(this);
}
return val;
}
}
function init(func) {
return function (target: any, propertyKey: string) {
let val = null;
let initializer = target[func];
let ran = false;
Object.defineProperty(target, propertyKey, {
get: function () {
if (!ran) {
ran = true;
initializer.call(this);
}
return val
},
set: function (newval) {
val = newval
},
enumerable: true,
configurable: true
})
}
}
class Tester {
c = 1;
@init('doInit')
test = 12
test2 = 14
doInit() {
console.log('runMeOnce');
}
get test2() {
return 12;
}
@once
runOnce() {
console.log('hi ', this.c++)
}
@memoize
getRandom() {
return Math.random();
}
}
let t = new Tester();
t.runOnce();
t.runOnce();
console.log(t.getRandom());
console.log(t.getRandom());
console.log(t.test)
console.log(t.test)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment