generated from antfu/starter-ts
-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: adds defineIdleProperty helper class (#9)
* chore: adds more strict type checking for idleValue class * feat: adds defineIdleProperty helper class --------- Co-authored-by: Harsh Kumar Choudhary <harsh.choudhary@HARSH-CHOUDHARY-MAC.local>
- Loading branch information
Showing
3 changed files
with
44 additions
and
12 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
import { defineIdleProperty } from './defineIdleProperty' | ||
|
||
export function defineIdleProperties<T, K extends PropertyKey>( // K for Key type | ||
obj: Record<K, any>, | ||
props: Record<K, () => T>, | ||
): void { | ||
Object.keys(props).forEach((propAsString) => { | ||
const prop = propAsString as K // Type assertion | ||
try { | ||
defineIdleProperty(obj, prop, props[prop]) | ||
} | ||
catch (error) { | ||
console.error(`Error defining idle property '${propAsString}':`, error) | ||
} | ||
}) | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
import { IdleValue } from './IdleValue' | ||
|
||
export function defineIdleProperty<T, TInitFunc extends () => T, K extends PropertyKey>( // Add K | ||
obj: Record<K, any>, | ||
prop: K, | ||
init: TInitFunc, | ||
): void { | ||
if (!obj || typeof obj !== 'object') | ||
throw new TypeError('obj must be an object') | ||
|
||
if (!prop) | ||
throw new Error('prop must be provided') | ||
|
||
const idleValue = new IdleValue<T, TInitFunc>(init) | ||
|
||
Object.defineProperty(obj, prop, { | ||
configurable: true, | ||
get: idleValue.getValue.bind(idleValue), | ||
set: idleValue.setValue.bind(idleValue), | ||
}) | ||
} |