Last active
June 3, 2023 12:54
-
-
Save tahakorkem/b6f6932c30245c00c5b4bcd3091a723a to your computer and use it in GitHub Desktop.
Lazy Loading Design Pattern in TypeScript
This file contains hidden or 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
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 | |
} | |
} |
This file contains hidden or 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
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