Last active
September 16, 2018 16:05
-
-
Save dotsonjb14/a29003783aa7dd472f3a7a1b533faf44 to your computer and use it in GitHub Desktop.
Typescript decorator for a once ran function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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