From 880a2ac368f5fa48b63b3fb16fc914547d612416 Mon Sep 17 00:00:00 2001 From: Abdelrahman Bahaa Date: Sun, 1 Dec 2024 04:24:42 +0200 Subject: [PATCH] refactor --- packages/runed/src/lib/utilities/Lazy/Lazy.spec.ts | 12 +++++------- packages/runed/src/lib/utilities/Lazy/Lazy.svelte.ts | 8 ++++---- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/packages/runed/src/lib/utilities/Lazy/Lazy.spec.ts b/packages/runed/src/lib/utilities/Lazy/Lazy.spec.ts index bf9ebaaf..be4140cd 100644 --- a/packages/runed/src/lib/utilities/Lazy/Lazy.spec.ts +++ b/packages/runed/src/lib/utilities/Lazy/Lazy.spec.ts @@ -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); }); }); diff --git a/packages/runed/src/lib/utilities/Lazy/Lazy.svelte.ts b/packages/runed/src/lib/utilities/Lazy/Lazy.svelte.ts index 496ac89b..93b92fa8 100644 --- a/packages/runed/src/lib/utilities/Lazy/Lazy.svelte.ts +++ b/packages/runed/src/lib/utilities/Lazy/Lazy.svelte.ts @@ -7,20 +7,20 @@ export class Lazy { 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; }