Skip to content

Commit

Permalink
Merge pull request #3 from cajames/better-cache-keygen
Browse files Browse the repository at this point in the history
  • Loading branch information
cajames committed Jan 29, 2024
2 parents b2b1cf0 + 0d5932c commit 2c9088a
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
39 changes: 39 additions & 0 deletions src/__tests__/lib.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,45 @@ describe("memorise", () => {
expect(testFn).toHaveBeenCalledTimes(1);
});

it("should treat undefined and null differently", () => {
const testFn = jest.fn();
const cachedFn = memorise(testFn);
cachedFn([undefined]);
cachedFn([null]);
expect(testFn).toHaveBeenCalledTimes(2);
});

it("should treat object with undefined values different to no keys at all", () => {
const testFn = jest.fn();
const cachedFn = memorise(testFn);
cachedFn({ a: undefined });
cachedFn({});
expect(testFn).toHaveBeenCalledTimes(2);
});

it("should support nested structures", () => {
const testFn = jest.fn();
const cachedFn = memorise(testFn);
cachedFn({ a: undefined });
cachedFn({});
expect(testFn).toHaveBeenCalledTimes(2);
});

it("should treat objects with same key,values equally, regardless of order", () => {
const testFn = jest.fn();
const cachedFn = memorise(testFn);
cachedFn({ a: 1, b: 2 });
cachedFn({ b: 2, a: 1 });
expect(testFn).toHaveBeenCalledTimes(1);
});

it("should treat single values and arrays differently", () => {
const testFn = jest.fn();
const cachedFn = memorise(testFn);
cachedFn(1);
cachedFn([1]);
expect(testFn).toHaveBeenCalledTimes(2);
});
// Later features
xit("should not cache a promise rejection when configured not to", async () => {});
xit("should cache an error when configured to", async () => {});
Expand Down
27 changes: 26 additions & 1 deletion src/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,5 +105,30 @@ const defaultGenCacheKey = (...args: any[]) => {
if (args.length === 0) {
return "no-args";
}
return args.map((val) => JSON.stringify(val)).join("/");
return args
.map((val) => {
if (val === undefined) {
return "undefined";
}
if (val === null) {
return "null";
}
if (Array.isArray(val)) {
return `[${defaultGenCacheKey(...val)}]`;
}
if (typeof val === "object") {
return `{${defaultGenCacheKey(...sortedObjectEntries(val))}}`;
}
return JSON.stringify(val);
})
.join(",");
};

const sortedObjectEntries = (obj: any) => {
return Object.entries(obj).sort((a, b) => {
if (a[0] < b[0]) {
return -1;
}
return 1;
});
};

0 comments on commit 2c9088a

Please sign in to comment.