Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
abdel-17 committed Dec 1, 2024
1 parent b30e69c commit 880a2ac
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
12 changes: 5 additions & 7 deletions packages/runed/src/lib/utilities/Lazy/Lazy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,24 @@ import { describe, vi } from "vitest";
import { Lazy } from "./Lazy.svelte.js";

describe("lazy", () => {
it("calls the initialization function only when current is initially accessed", () => {
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);

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

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

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

it("does not call the initialization function when current is set", () => {
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(init).toHaveBeenCalledTimes(0);
expect(counter.current).toBe(1);
expect(init).toHaveBeenCalledTimes(0);
});
});
8 changes: 4 additions & 4 deletions packages/runed/src/lib/utilities/Lazy/Lazy.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,20 @@ export class Lazy<T> {
this.#init = init;
}

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

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

set current(value: T) {
set current(value) {
this.#current = value;
this.#initialized = true;
}
Expand Down

0 comments on commit 880a2ac

Please sign in to comment.