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
15 changes: 15 additions & 0 deletions packages/normalize-color/__tests__/normalizeColor-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
});
9 changes: 3 additions & 6 deletions packages/normalize-color/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading