Skip to content

Commit

Permalink
fix(property-provider): memoize provider after the first evoke instea…
Browse files Browse the repository at this point in the history
…d of immediately (#1471)
  • Loading branch information
AllanZhengYP committed Aug 27, 2020
1 parent 0ca7227 commit 729a276
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
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;
}
return result;
};
}

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

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

0 comments on commit 729a276

Please sign in to comment.