Skip to content

Instantly share code, notes, and snippets.

@tahakorkem
Last active June 3, 2023 12:54
Show Gist options
  • Save tahakorkem/b6f6932c30245c00c5b4bcd3091a723a to your computer and use it in GitHub Desktop.
Save tahakorkem/b6f6932c30245c00c5b4bcd3091a723a to your computer and use it in GitHub Desktop.
Lazy Loading Design Pattern in TypeScript
export class Lazy<T> {
private _value?: T
constructor(private initializer: () => T) {
}
get value(): T {
if (this._value == undefined) {
this._value = this.initializer()
}
return this._value
}
set value(newValue: T) {
this._value = newValue
}
}
import {Lazy} from "....";
const calculated: Lazy<number> = new Lazy(() => power(99, 99))
// power function will be called only once, when you access calculated.value at the first time
function power(num: number, exp: number) {
let ans = 1;
for(let i = 0; i<exp; i++) {
ans *= num
}
console.log(num + " to " + exp + " calculated as " + ans)
return ans
}
console.log("before first call")
console.log(calculated.value)
console.log(calculated.value)
console.log(calculated.value)
console.log("after last call")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment