Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@
"url": "https://github.com/webdeveric/utils/issues"
},
"homepage": "https://github.com/webdeveric/utils/#readme",
"packageManager": "pnpm@11.22.0+sha512.1ff870c4c6133dfd88fb2afc46dd13d47f09c9794b438c6fdb47ca98caf3bc16381ee0be93a091b8e3824cf01f889f46d7d9e20910fb0be1ab0fb5baa80dd621",
"packageManager": "pnpm@11.25.0+sha512.5cde925b4f075f725eb71fbae18a42ffe784524789f19b61c731cb8721ec28aaee160e01a8d5af4fedb2a42cdbf300efe23db356b0d4a17b4d63e11f8ab7c956",
"scripts": {
"clean": "rimraf ./dist/ ./cache/ ./coverage/",
"prebuild": "pnpm clean",
Expand Down Expand Up @@ -97,20 +97,20 @@
"commitlint": "^21.2.2",
"commitlint-plugin-cspell": "^0.9.4",
"conventional-changelog-conventionalcommits": "^9.3.1",
"cspell": "^10.0.1",
"cspell": "^10.1.1",
"eslint": "^8.57.1",
"eslint-config-prettier": "^10.1.8",
"eslint-import-resolver-typescript": "^4.4.5",
"eslint-plugin-import": "^2.32.0",
"husky": "^9.1.7",
"jsdom": "^30.0.1",
"lint-staged": "^17.3.0",
"lint-staged": "^17.4.1",
"prettier": "^3.9.6",
"rimraf": "^6.1.3",
"semantic-release": "^25.0.9",
"typedoc": "^0.28.20",
"typescript": "npm:@typescript/typescript6@^6.0.2",
"validate-package-exports": "^1.3.3",
"validate-package-exports": "^1.4.0",
"vitest": "^4.1.11"
}
}
610 changes: 314 additions & 296 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,5 +12,8 @@ engineStrict: true

minimumReleaseAge: 2880 # 2 days

overrides:
nanoid@<3.3.18: ^3.3.18

update:
githubActions: true
2 changes: 2 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export * from './isEmpty.js';
export * from './iterateForever.js';
export * from './joinStrings.js';
export * from './jsonParse.js';
export * from './lazyProp.js';
export * from './lazyRecord.js';
export * from './looksLikeURL.js';
export * from './memo.js';
export * from './normalize.js';
Expand Down
31 changes: 31 additions & 0 deletions src/lazyProp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* Create a property descriptor that lazily computes its value.
*
* @example
* ```ts
* const data = {};
*
* Object.defineProperty(data, 'value', lazyProp('value', () => {
* return Math.random();
* }));
* ```
*/
export function lazyProp<Key extends PropertyKey, Value>(
key: Key,
getter: () => Value,
): TypedPropertyDescriptor<Value> {
return {
configurable: true,
get() {
const value = getter();

Object.defineProperty(this, key, {
value,
writable: true,
configurable: true,
});

return value;
},
};
}
41 changes: 41 additions & 0 deletions src/lazyRecord.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { lazyProp } from './lazyProp.js';

import type { AnyFunction } from './types/common.js';
import type { UnknownRecord } from './types/records.js';

export type LazyRecordProperties<Type extends UnknownRecord> = {
[Key in keyof Type]: Exclude<Type[Key], AnyFunction> | (() => Type[Key]);
};

/**
* Create an object whose properties are computed lazily.
*
* @example
* ```ts
* const data = lazyRecord({
* name: 'Name',
* now() {
* return Date.now();
* },
* });
* ```
*/
export function lazyRecord<Type extends UnknownRecord>(properties: LazyRecordProperties<Type>): Type {
const record = Object.create(null);

for (const [key, getter] of Object.entries(properties)) {
Object.defineProperty(
record,
key,
typeof getter === 'function'
? lazyProp(key, getter)
: {
value: getter,
writable: true,
configurable: true,
},
);
}

return record;
}
67 changes: 67 additions & 0 deletions test/lazyProp.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { describe, expect, it, vi } from 'vitest';

import { lazyProp } from '../src/lazyProp.js';

import type { UnknownRecord } from '../src/types/records.js';

describe('lazyProp()', () => {
it('Does not call the getter until the property is accessed', () => {
const getter = vi.fn(() => 'value');
const data: UnknownRecord = {};

Object.defineProperty(data, 'value', lazyProp('value', getter));

expect(getter).not.toHaveBeenCalled();

expect(data['value']).toBe('value');

expect(getter).toHaveBeenCalledTimes(1);
});

it('Only calls the getter once', () => {
const getter = vi.fn(() => Math.random());
const data: UnknownRecord = {};

Object.defineProperty(data, 'value', lazyProp('value', getter));

const first = data['value'];
const second = data['value'];

expect(getter).toHaveBeenCalledTimes(1);
expect(first).toBe(second);
});

it('Replaces the property with a plain, writable, configurable value', () => {
const getter = vi.fn(() => 'computed');
const data: UnknownRecord = {};

Object.defineProperty(data, 'value', lazyProp('value', getter));

void data['value'];

const descriptor = Object.getOwnPropertyDescriptor(data, 'value');

expect(descriptor).toMatchObject({
value: 'computed',
writable: true,
configurable: true,
enumerable: false,
});

data['value'] = 'updated';

expect(data['value']).toBe('updated');
expect(getter).toHaveBeenCalledTimes(1);
});

it('Works with symbol keys', () => {
const key = Symbol('value');
const getter = vi.fn(() => 'symbol value');
const data: UnknownRecord = {};

Object.defineProperty(data, key, lazyProp(key, getter));

expect(data[key]).toBe('symbol value');
expect(getter).toHaveBeenCalledTimes(1);
});
});
91 changes: 91 additions & 0 deletions test/lazyRecord.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { describe, expect, it, vi } from 'vitest';

import { lazyRecord } from '../src/lazyRecord.js';

describe('lazyRecord()', () => {
it('Does not call getter functions until the property is accessed', () => {
const computed = vi.fn(() => 'computed');

const record = lazyRecord({
name: 'Name',
computed,
});

expect(computed).not.toHaveBeenCalled();

expect(record.name).toBe('Name');
expect(record.computed).toBe('computed');

expect(computed).toHaveBeenCalledTimes(1);
});

it('Only calls each getter once', () => {
const random = vi.fn(() => Math.random());

const record = lazyRecord({
random,
});

const first = record.random;
const second = record.random;

expect(random).toHaveBeenCalledTimes(1);
expect(first).toBe(second);
});

it('Keeps plain, non-function values as-is', () => {
const record = lazyRecord({
name: 'Name',
count: 1,
});

expect(record.name).toBe('Name');
expect(record.count).toBe(1);
});

it('Returns properties that are writable and configurable', () => {
const record = lazyRecord({
name: 'Name',
computed: () => 'computed',
});

// Access `computed` so its descriptor gets replaced by the getter's `defineProperty()` call.
void record.computed;

record.name = 'Updated';
record.computed = 'Updated';

expect(record.name).toBe('Updated');
expect(record.computed).toBe('Updated');
});

it('Has a null prototype', () => {
const record = lazyRecord({
name: 'Name',
});

expect(Object.getPrototypeOf(record)).toBeNull();
});

it('Exposes all keys passed in', () => {
const record = lazyRecord({
name: 'Name',
now: () => Date.now(),
});

// Properties are non-enumerable until accessed, so use `getOwnPropertyNames()` instead of `keys()`.
expect(Object.getOwnPropertyNames(record)).toEqual(['name', 'now']);
});

it('Can be a prototype for another object', () => {
const record = lazyRecord({
name: 'Name',
now: () => Date.now(),
});

const child = Object.create(record);

expect(child.name).toBe('Name');
expect(typeof child.now).toBe('number');
});
});