Skip to content
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
43 changes: 35 additions & 8 deletions src/js/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,19 +125,44 @@ export const setCache = (key: string, value: unknown): void => {
* @param key - cache key
* @returns cached item or false otherwise
*/
export const getCache = (key: string): CacheItem | boolean => {
if (key && genCache.has(key)) {
const item = genCache.get(key);
export const getCache = (key: string): CacheItem | false => {
if (!key) {
return false;
}

const item = genCache.get(key);
if (item !== undefined) {
if (item instanceof CacheItem) {
return item;
}
// delete unexpected cached item
genCache.delete(key);
return false;
}

return false;
};

/**
* helper function to sort object keys alphabetically
* @param obj - Object
* @returns stringified JSON
*/
const stringifySorted = (obj: Record<string, unknown>): string => {
const keys = Object.keys(obj).sort();
if (keys.length === 0) {
return '';
}
return JSON.stringify(
keys.reduce(
(acc, key) => {
acc[key] = obj[key];
return acc;
},
{} as Record<string, unknown>
)
);
};

/**
* create cache key
* @param keyData - key data
Expand Down Expand Up @@ -168,9 +193,11 @@ export const createCacheKey = (
opt.preserveComment ? '1' : '0',
String(opt.delimiter || '')
].join('|');
const customPropStr = Object.keys(customProperty).length
? JSON.stringify(customProperty)
: '';
const dimStr = Object.keys(dimension).length ? JSON.stringify(dimension) : '';

const customPropStr = stringifySorted(
customProperty as Record<string, unknown>
);
const dimStr = stringifySorted(dimension as Record<string, unknown>);

return `${baseKey}::${optStr}::${customPropStr}::${dimStr}`;
};
2 changes: 1 addition & 1 deletion test/cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ describe('create cache key', () => {
);
assert.strictEqual(
res,
'foo:bar:baz::computedValue|srgb|normal|black|0|0|1| ::{"--foo":"foo","--bar":"bar"}::{"em":12,"rem":16}',
'foo:bar:baz::computedValue|srgb|normal|black|0|0|1| ::{"--bar":"bar","--foo":"foo"}::{"em":12,"rem":16}',
'result'
);
});
Expand Down
Loading