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

Correct createLatest triggering on equals: false #520

Merged
merged 1 commit into from
Oct 6, 2023
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
5 changes: 5 additions & 0 deletions .changeset/little-mails-obey.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@solid-primitives/memo": patch
---

Correct `createLatest` and `createLatestMany` triggering on `equals: false` sources
89 changes: 24 additions & 65 deletions packages/memo/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
} from "solid-js";
import { isServer } from "solid-js/web";
import { debounce, throttle } from "@solid-primitives/scheduled";
import { noop, EffectOptions } from "@solid-primitives/utils";
import { noop, EffectOptions, EQUALS_FALSE_OPTIONS } from "@solid-primitives/utils";

export type MemoOptionsWithValue<T> = MemoOptions<T> & { value?: T };
export type AsyncMemoCalculation<T, Init = undefined> = (prev: T | Init) => Promise<T> | T;
Expand Down Expand Up @@ -106,7 +106,13 @@ export function createLatest<T extends readonly Accessor<any>[]>(
options?: MemoOptions<ReturnType<T[number]>>,
): Accessor<ReturnType<T[number]>> {
let index = 0;
const memos = sources.map((source, i) => createMemo(() => ((index = i), source())));
const memos = sources.map((source, i) =>
createMemo(
() => ((index = i), source()),
undefined,
DEV ? { name: i + 1 + ". source", equals: false } : EQUALS_FALSE_OPTIONS,
),
);
return createMemo(() => memos.map(m => m())[index]!, undefined, options);
}

Expand All @@ -131,18 +137,25 @@ export function createLatestMany<T>(
sources: readonly Accessor<T>[],
options?: EffectOptions,
): Accessor<T[]> {
const mappedSources = sources.map(source => {
const obj: { dirty: boolean; memo: Accessor<T> } = { dirty: true, memo: null as any };
obj.memo = createMemo(() => ((obj.dirty = true), source()));
const memos = sources.map((source, i) => {
const obj = { dirty: true, get: null as any as Accessor<T> };

obj.get = createMemo(
() => ((obj.dirty = true), source()),
undefined,
DEV ? { name: i + 1 + ". source", equals: false } : EQUALS_FALSE_OPTIONS,
);

return obj;
});

return createLazyMemo<T[]>(
() =>
mappedSources.reduce((acc: T[], data) => {
memos.reduce((acc: T[], memo) => {
// always track all memos to force updates
const v = data.memo();
if (data.dirty) {
data.dirty = false;
const v = memo.get();
if (memo.dirty) {
memo.dirty = false;
acc.push(v);
}
return acc;
Expand Down Expand Up @@ -348,8 +361,6 @@ export function createAsyncMemo<T>(
return state;
}

const EQUALS_FALSE = { equals: false } as const;

/**
* Lazily evaluated `createMemo`. Will run the calculation only if is being listened to.
*
Expand Down Expand Up @@ -394,11 +405,11 @@ export function createLazyMemo<T>(
let isReading = false,
isStale: boolean | undefined = true;

const [track, trigger] = createSignal(void 0, EQUALS_FALSE),
const [track, trigger] = createSignal(void 0, EQUALS_FALSE_OPTIONS),
memo = createMemo<T>(
p => (isReading ? calc(p) : ((isStale = !track()), p)),
value as T,
DEV ? { name: options?.name, equals: false } : EQUALS_FALSE,
DEV ? { name: options?.name, equals: false } : EQUALS_FALSE_OPTIONS,
);

return (): T => {
Expand All @@ -410,58 +421,6 @@ export function createLazyMemo<T>(
};
}

/*

createCachedDerivation is a cool idea, but it has a n edgecase where it the value may get out of sync if read in a pure computation after it's sources.
And probably more then that, considering that the calculation is executed where read.

*/

// /**
// * **! The value may get out of sync if read in a pure computation after it's sources !**
// * @param deps
// * @param fn
// * @param options
// * @returns
// */
// export function createCachedDerivation<S, Next extends Prev, Prev = Next>(
// deps: AccessorArray<S> | Accessor<S>,
// fn: OnEffectFunction<S, undefined | NoInfer<Prev>, Next>,
// options?: EffectOptions
// ): Accessor<Next> {
// let prevInput: S | undefined;
// let prev: undefined | NoInfer<Prev>;
// let stale = true;

// const track = createPureReaction(() => (stale = true), options);

// const trackDeps = Array.isArray(deps)
// ? () => {
// for (const fn of deps) fn();
// }
// : deps;

// const getInput = Array.isArray(deps)
// ? () => {
// const res = Array(deps.length);
// for (let i = 0; i < deps.length; i++) res[i] = deps[i]();
// return res as S;
// }
// : deps;

// return () => {
// if (stale) {
// let input!: S;
// track(() => (input = getInput()));
// prev = untrack(() => fn(input, prevInput, prev));
// prevInput = input;
// stale = false;
// }
// trackDeps();
// return prev as Next;
// };
// }

export type CacheCalculation<Key, Value> = (key: Key, prev: Value | undefined) => Value;
export type CacheKeyAccessor<Key, Value> = (key: Key) => Value;
export type CacheOptions<Value> = MemoOptions<Value> & { size?: number };
Expand Down
92 changes: 91 additions & 1 deletion packages/memo/test/latest.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, test, expect } from "vitest";
import { batch, createRoot, createSignal } from "solid-js";
import { batch, createEffect, createRoot, createSignal } from "solid-js";
import { createLatest, createLatestMany } from "../src/index.js";

describe("createLatest", () => {
Expand Down Expand Up @@ -27,6 +27,66 @@ describe("createLatest", () => {
dispose();
});
});

test("works with equals: false sources", () => {
const [a, setA] = createSignal(0, { equals: false });
const [b, setB] = createSignal("b");
let captured: any;

const dispose = createRoot(dispose => {
const latest = createLatest([a, b]);
createEffect(() => {
captured = latest();
});
return dispose;
});

expect(captured).toBe("b");
captured = undefined;

setA(1);
expect(captured).toBe(1);
captured = undefined;

setB("c");
expect(captured).toBe("c");
captured = undefined;

setA(1);
expect(captured).toBe(1);

dispose();
});

test("equals options", () => {
const [a, setA] = createSignal(0);
const [b, setB] = createSignal("b");

const { latest, dispose } = createRoot(dispose => {
return {
latest: createLatest([a, b], {
equals: (a, b) => typeof b === "number",
}),
dispose,
};
});

expect(latest()).toBe("b");

setA(1);
expect(latest()).toBe("b");

setB("c");
expect(latest()).toBe("c");

setA(2);
expect(latest()).toBe("c");

setB("d");
expect(latest()).toBe("d");

dispose();
});
});

describe("createLatestMany", () => {
Expand Down Expand Up @@ -54,4 +114,34 @@ describe("createLatestMany", () => {
dispose();
});
});

test("works with equals: false sources", () => {
const [a, setA] = createSignal(0, { equals: false });
const [b, setB] = createSignal("b");
let captured: any;

const dispose = createRoot(dispose => {
const latest = createLatestMany([a, b]);
createEffect(() => {
captured = latest();
});
return dispose;
});

expect(captured).toEqual([0, "b"]);
captured = undefined;

setA(1);
expect(captured).toEqual([1]);
captured = undefined;

setB("c");
expect(captured).toEqual(["c"]);
captured = undefined;

setA(1);
expect(captured).toEqual([1]);

dispose();
});
});