Skip to content

Commit d517751

Browse files
authored
Merge pull request #42 from jviide/custom-jsx-parser-04
Use JSON.stringify for cache key generation
2 parents e42f58d + 13c3123 commit d517751

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

src/index.mjs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,11 @@
1313

1414
const CACHE = {};
1515

16+
const stringify = JSON.stringify;
17+
1618
export default function html(statics) {
17-
const key = statics.length + statics;
19+
let key = '.';
20+
for (let i=0; i<statics.length; i++) key += statics[i].length + ',' + statics[i];
1821
const tpl = CACHE[key] || (CACHE[key] = build(statics));
1922

2023
// eslint-disable-next-line prefer-rest-params
@@ -55,12 +58,12 @@ const build = (statics) => {
5558
if (!inTag) {
5659
if (field || (buffer = buffer.replace(/^\s*\n\s*|\s*\n\s*$/g,''))) {
5760
if (hasChildren++) out += ',';
58-
out += field || JSON.stringify(buffer);
61+
out += field || stringify(buffer);
5962
}
6063
}
6164
else if (mode === MODE_TAGNAME) {
6265
if (hasChildren++) out += ',';
63-
out += 'h(' + (field || JSON.stringify(buffer));
66+
out += 'h(' + (field || stringify(buffer));
6467
mode = MODE_WHITESPACE;
6568
}
6669
else if (mode === MODE_ATTRIBUTE || (mode === MODE_WHITESPACE && buffer === '...')) {
@@ -77,8 +80,8 @@ const build = (statics) => {
7780
if (!props) props += '{';
7881
else props += ',' + (propsClose ? '' : '{');
7982
propsClose = '}';
80-
props += JSON.stringify(propName) + ':';
81-
props += field || ((propHasValue || buffer) && JSON.stringify(buffer)) || 'true';
83+
props += stringify(propName) + ':';
84+
props += field || ((propHasValue || buffer) && stringify(buffer)) || 'true';
8285
propName = '';
8386
}
8487
propHasValue = false;

test/index.test.mjs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,5 +164,7 @@ describe('htm', () => {
164164
test('cache key should be unique', () => {
165165
html`<a b="${'foo'}" />`;
166166
expect(html`<a b="\0" />`).toEqual(h('a', { b: '\0' }));
167+
expect(html`<a>${''}9aaaaaaaaa${''}</a>`).not.toEqual(html`<a>${''}0${''}aaaaaaaaa${''}</a>`);
168+
expect(html`<a>${''}0${''}aaaaaaaa${''}</a>`).not.toEqual(html`<a>${''}.8aaaaaaaa${''}</a>`);
167169
});
168170
});

0 commit comments

Comments
 (0)