diff --git a/packages/normalize-color/__tests__/normalizeColor-test.js b/packages/normalize-color/__tests__/normalizeColor-test.js index ab84c6d3d327..166b86e796eb 100644 --- a/packages/normalize-color/__tests__/normalizeColor-test.js +++ b/packages/normalize-color/__tests__/normalizeColor-test.js @@ -177,3 +177,18 @@ it('returns the same color when it is already normalized', () => { const normalizedColor = normalizeColor('red') || 0; expect(normalizeColor(normalizedColor)).toBe(normalizedColor); }); + +it('returns a cached 0 or null without parsing again', () => { + for (const [color, expected] of [ + ['#0000', 0x00000000], + ['not a color', null], + ]) { + expect(normalizeColor(color)).toBe(expected); + const exec = jest.spyOn(RegExp.prototype, 'exec'); + const cached = normalizeColor(color); + const execCalls = exec.mock.calls.length; + exec.mockRestore(); + expect(cached).toBe(expected); + expect(execCalls).toBe(0); + } +}); diff --git a/packages/normalize-color/index.js b/packages/normalize-color/index.js index d4ea4682eebe..246d8288e8b8 100644 --- a/packages/normalize-color/index.js +++ b/packages/normalize-color/index.js @@ -26,12 +26,9 @@ function normalizeColor(color) { return null; } - if (cachedColors.has(color)) { - // Map iteration order follows insertion order, so re-inserting on every - // hit keeps the least-recently-used entry first. - const cachedColor = cachedColors.get(color); - cachedColors.delete(color); - cachedColors.set(color, cachedColor); + // A single get() is faster than LRU and most apps don't fill the color cache + const cachedColor = cachedColors.get(color); + if (cachedColor !== undefined) { return cachedColor; } const normalizedColor = parseColorString(color);