Skip to content

Commit

Permalink
Support optimistic.forget to remove Entry objects from Cache (#84)
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamn authored Oct 13, 2020
1 parent 709e28c commit cda0228
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
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);
});
});

0 comments on commit cda0228

Please sign in to comment.