Skip to content

Commit

Permalink
refactor: flattenToken use WeakMap
Browse files Browse the repository at this point in the history
  • Loading branch information
zombieJ committed Aug 27, 2023
1 parent eeb7455 commit ab8fc3d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 14 deletions.
33 changes: 21 additions & 12 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,28 @@ import canUseDom from 'rc-util/lib/Dom/canUseDom';
import { removeCSS, updateCSS } from 'rc-util/lib/Dom/dynamicCSS';
import { Theme } from './theme';

// Create a cache here to avoid always loop generate
const flattenTokenCache = new WeakMap<any, string>();

export function flattenToken(token: any) {
let str = '';
Object.keys(token).forEach((key) => {
const value = token[key];
str += key;
if (value instanceof Theme) {
str += value.id;
} else if (value && typeof value === 'object') {
str += flattenToken(value);
} else {
str += value;
}
});
let str = flattenTokenCache.get(token) || '';

if (!str) {
Object.keys(token).forEach((key) => {
const value = token[key];
str += key;
if (value instanceof Theme) {
str += value.id;
} else if (value && typeof value === 'object') {
str += flattenToken(value);
} else {
str += value;
}
});

// Put in cache
flattenTokenCache.set(token, str);
}
return str;
}

Expand Down
26 changes: 24 additions & 2 deletions tests/util.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { normalizeStyle, parseStyle } from '../src/hooks/useStyleRegister';
import { flattenToken } from '../src/util';

vi.mock('../src/util', () => {
const origin = vi.importActual('../src/util');
vi.mock('../src/util', async () => {
const origin: any = await vi.importActual('../src/util');
return {
...origin,
supportLayer: () => true,
Expand Down Expand Up @@ -104,4 +105,25 @@ describe('util', () => {
});
});
});

it('flattenToken should support cache', () => {
const token = {};

let checkTimes = 0;
Object.defineProperty(token, 'a', {
get() {
checkTimes += 1;
return 1;
},
enumerable: true,
});

// Repeat call flattenToken
for (let i = 0; i < 10000; i += 1) {
const tokenStr = flattenToken(token);
expect(tokenStr).toEqual('a1');
}

expect(checkTimes).toEqual(1);
});
});

0 comments on commit ab8fc3d

Please sign in to comment.