diff --git a/src/js/cache.ts b/src/js/cache.ts index 8b159f5..1414403 100644 --- a/src/js/cache.ts +++ b/src/js/cache.ts @@ -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 => { + 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 + ) + ); +}; + /** * create cache key * @param keyData - key data @@ -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 + ); + const dimStr = stringifySorted(dimension as Record); + return `${baseKey}::${optStr}::${customPropStr}::${dimStr}`; }; diff --git a/test/cache.test.ts b/test/cache.test.ts index bcf21bf..e9df203 100644 --- a/test/cache.test.ts +++ b/test/cache.test.ts @@ -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' ); });