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 optimistic.forget to remove Entry objects from Cache. #84

Merged
merged 3 commits into from
Oct 13, 2020
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
7 changes: 7 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ export type OptimisticWrapperFunction<
dirty: (...args: TKeyArgs) => void;
// Examine the current value without recomputing it.
peek: (...args: TKeyArgs) => TResult | undefined;
// Remove the entry from the cache, dirtying any parent entries.
forget: (...args: TKeyArgs) => boolean;
};

export type OptimisticWrapOptions<
Expand Down Expand Up @@ -149,5 +151,10 @@ export function wrap<
}
};

optimistic.forget = function () {
const key = makeCacheKey.apply(null, arguments as any);
return key !== void 0 && cache.delete(key);
};

return optimistic as OptimisticWrapperFunction<TArgs, TResult, TKeyArgs>;
}
40 changes: 40 additions & 0 deletions src/tests/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -579,4 +579,44 @@ describe("optimism", function () {
// Since 6 < 7, its value is still cached.
assert.strictEqual(sumFirst.peek(6), 6 * 7 / 2);
});

it("allows forgetting entries", function () {
const ns: number[] = [];
const sumFirst = wrap(function (n: number): number {
ns.push(n);
return n < 1 ? 0 : n + sumFirst(n - 1);
});

function inclusiveDescendingRange(n: number, limit = 0) {
const range: number[] = [];
while (n >= limit) range.push(n--);
return range;
}

assert.strictEqual(sumFirst(10), 55);
assert.deepStrictEqual(ns, inclusiveDescendingRange(10));

assert.strictEqual(sumFirst.forget(6), true);
assert.strictEqual(sumFirst(4), 10);
assert.deepStrictEqual(ns, inclusiveDescendingRange(10));

assert.strictEqual(sumFirst(11), 66);
assert.deepStrictEqual(ns, [
...inclusiveDescendingRange(10),
...inclusiveDescendingRange(11, 6),
]);

assert.strictEqual(sumFirst.forget(3), true);
assert.strictEqual(sumFirst(7), 28);
assert.deepStrictEqual(ns, [
...inclusiveDescendingRange(10),
...inclusiveDescendingRange(11, 6),
...inclusiveDescendingRange(7, 3),
]);

assert.strictEqual(sumFirst.forget(123), false);
assert.strictEqual(sumFirst.forget(-1), false);
assert.strictEqual(sumFirst.forget("7" as any), false);
assert.strictEqual((sumFirst.forget as any)(6, 4), false);
});
});