Skip to content

Commit 1f992e8

Browse files
committed
Use Map for caching when available
Use Map for caching when available, otherwise fall back to the old caching scheme based on string keys. These changes were code-golfed to their current form together with @developit.
1 parent 0608217 commit 1f992e8

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/index.mjs

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,29 @@
1212
*/
1313

1414
import { build, evaluate } from './build.mjs';
15-
16-
const CACHE = {};
1715

18-
export default function html(statics) {
19-
let key = '.';
20-
for (let i=0; i<statics.length; i++) {
21-
key += statics[i].length + ',' + statics[i];
16+
const getCacheMap = (statics) => {
17+
let tpl = CACHE.get(statics);
18+
if (!tpl) {
19+
CACHE.set(statics, tpl = build(statics));
2220
}
23-
const tpl = CACHE[key] || (CACHE[key] = build(statics));
21+
return tpl;
22+
};
2423

24+
const getCache = (statics) => {
25+
let key = '';
26+
for (let i = 0; i < statics.length; i++) {
27+
key += statics[i].length + '-' + statics[i];
28+
}
29+
return CACHE[key] || (CACHE[key] = build(statics));
30+
};
31+
32+
const USE_MAP = typeof Map === 'function';
33+
const CACHE = USE_MAP ? new Map() : {};
34+
const cached = USE_MAP ? getCacheMap : getCache;
35+
36+
export default function htm(statics) {
2537
// eslint-disable-next-line prefer-rest-params
26-
const res = evaluate(this, tpl, arguments, []);
38+
const res = evaluate(this, cached(statics), arguments, []);
2739
return res.length > 1 ? res : res[0];
2840
}

0 commit comments

Comments
 (0)