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

Support options.normalizeResult callback in wrap(fn, options) to allow reconciling newly computed results with previous results #283

Merged
merged 1 commit into from
Nov 29, 2023

Conversation

benjamn
Copy link
Owner

@benjamn benjamn commented Sep 15, 2021

Sometimes a function cached with optimism will be spuriously dirtied (directly or indirectly) in a way that triggers recomputation the next time the function is called. The newly computed result may be logically different from the previous result, of course, but if the two results are equivalent (or share equivalent subparts), the developer may wish to keep using (parts of) the previous result.

To take advantage of this system for reconciling cached results, pass an options.normalizeResult callback in the options for the wrap function:

// Use any deep equality test you like:
import { equal } from "@wry/equality"

const range = wrap((n: number): number[] => {
  return n > 0 ? range(n - 1).concat(n - 1) : [];
}, {
  normalizeResult(newer: number[], older: number[]) {
    return equal(newer, older) ? older : newer;
  },
});

Normally, this function would always return the newer array, but using normalizeResult allows the optimism system to continue using older in cases where equal(newer, older), which helps limit referential diversity of range arrays over time.

Since this normalizeResult system works within optimism, at each level of the dependency graph, it should be able to provide referential stability benefits similar to those promised by cache result canonization (apollographql/apollo-client#7439), without using nearly as much memory.

@benjamn benjamn self-assigned this Sep 15, 2021
@benjamn benjamn changed the title Support options.normalizeResult callback in wrap(fn, options) to allow coalescing newly computed results with previous results Support options.normalizeResult callback in wrap(fn, options) to allow reconciling newly computed results with previous results Sep 15, 2021
@benjamn benjamn force-pushed the feat/wrap-options.normalizeResult branch from 1db011c to b720500 Compare March 21, 2023 21:57
@benjamn benjamn force-pushed the feat/wrap-options.normalizeResult branch from b720500 to b56904b Compare November 29, 2023 16:53
@benjamn benjamn merged commit 83f0f72 into main Nov 29, 2023
5 checks passed
@benjamn benjamn deleted the feat/wrap-options.normalizeResult branch November 29, 2023 16:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant