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

fix(property-provider): memoize provider after the first evoke #1471

Merged
merged 1 commit into from
Aug 27, 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
4 changes: 3 additions & 1 deletion packages/property-provider/src/memoize.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ describe("memoize", () => {

describe("static memoization", () => {
it("should cache the resolved provider", async () => {
expect.assertions(repeatTimes * 2);
expect.assertions(repeatTimes * 2 + 1);

const memoized = memoize(provider);
expect(provider).toHaveBeenCalledTimes(0);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const index in [...Array(repeatTimes).keys()]) {
expect(await memoized()).toStrictEqual(mockReturn);
Expand Down Expand Up @@ -51,6 +52,7 @@ describe("memoize", () => {
const isExpiredFalseTest = async (requiresRefresh?: any) => {
isExpired.mockReturnValue(false);
const memoized = memoize(provider, isExpired, requiresRefresh);
expect(provider).toHaveBeenCalledTimes(0);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
for (const index in [...Array(repeatTimes).keys()]) {
expect(await memoized()).toEqual(mockReturn);
Expand Down
16 changes: 13 additions & 3 deletions packages/property-provider/src/memoize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,26 @@ export const memoize: MemoizeOverload = <T>(
isExpired?: (resolved: T) => boolean,
requiresRefresh?: (resolved: T) => boolean
): Provider<T> => {
let result: any;
let hasResult: boolean;
if (isExpired === undefined) {
// This is a static memoization; no need to incorporate refreshing
const result = provider();
return () => result;
return () => {
if (!hasResult) {
result = provider();
hasResult = true;
}
trivikr marked this conversation as resolved.
Show resolved Hide resolved
return result;
};
}

let result = provider();
let isConstant = false;

return async () => {
if (!hasResult) {
result = provider();
hasResult = true;
}
if (isConstant) {
return result;
}
Expand Down