Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Lazy #143

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
25 changes: 25 additions & 0 deletions packages/runed/src/lib/utilities/Lazy/Lazy.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { describe, vi } from "vitest";
import { Lazy } from "./Lazy.svelte.js";

describe("lazy", () => {
it("calls the initialization function only when `current` is first accessed", () => {
const init = vi.fn(() => 0);
const counter = new Lazy(init);
expect(init).toHaveBeenCalledTimes(0);

expect(counter.current).toBe(0);
expect(init).toHaveBeenCalledTimes(1);

expect(counter.current).toBe(0);
expect(init).toHaveBeenCalledTimes(1);
});

it("does not call the initialization function when `current` is set", () => {
const init = vi.fn(() => 0);
const counter = new Lazy(init);

counter.current = 1;
expect(counter.current).toBe(1);
expect(init).toHaveBeenCalledTimes(0);
});
});
27 changes: 27 additions & 0 deletions packages/runed/src/lib/utilities/Lazy/Lazy.svelte.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { untrack } from "svelte";

export class Lazy<T> {
#init: () => T;

constructor(init: () => T) {
this.#init = init;
}

#current: T = $state()!;
#initialized = false;

get current() {
if (!this.#initialized) {
untrack(() => {
this.#current = this.#init();
this.#initialized = true;
});
}
return this.#current;
}

set current(value) {
this.#current = value;
this.#initialized = true;
}
}
1 change: 1 addition & 0 deletions packages/runed/src/lib/utilities/Lazy/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { Lazy } from "./Lazy.svelte.js";
1 change: 1 addition & 0 deletions packages/runed/src/lib/utilities/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ export * from "./AnimationFrames/index.js";
export * from "./useIntersectionObserver/index.js";
export * from "./IsFocusWithin/index.js";
export * from "./FiniteStateMachine/index.js";
export * from "./Lazy/index.js";