From 6d1ac67bff40ed79ffe35476658a56aae17ed038 Mon Sep 17 00:00:00 2001 From: PalmDevs Date: Mon, 2 Jun 2025 15:48:06 +0700 Subject: [PATCH] feat(utils/objects): add `defineLazyProperty` --- lib/utils/src/objects.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/lib/utils/src/objects.ts b/lib/utils/src/objects.ts index dd68e53..cda7da7 100644 --- a/lib/utils/src/objects.ts +++ b/lib/utils/src/objects.ts @@ -94,3 +94,20 @@ export function mergeDeep(target: AnyObject, source: AnyObject) { return target } + +/** + * Define a lazy property on an object that will be loaded when accessed. + * + * @param target The target object to define the property on. + * @param property The property key to define. + * @param loader The function that will be called to load the property value when accessed. + */ +export function defineLazyProperty(target: T, property: K, loader: () => T[K]) { + Object.defineProperty(target, property, { + configurable: true, + get() { + delete target[property] + return (target[property] = loader()) + }, + }) +}