Skip to content

Commit 16df0e4

Browse files
Merge pull request #184 from preactjs/encode-perf
2 parents ced65a7 + ab73d3f commit 16df0e4

File tree

2 files changed

+29
-5
lines changed

2 files changed

+29
-5
lines changed

src/index.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ const UNNAMED = [];
1515

1616
const VOID_ELEMENTS = /^(area|base|br|col|embed|hr|img|input|link|meta|param|source|track|wbr)$/;
1717

18+
const UNSAFE_NAME = /[\s\n\\/='"\0<>]/;
19+
1820
const noop = () => {};
1921

2022
/** Render Preact JSX + Components to an HTML string.
@@ -291,12 +293,12 @@ function _renderToString(vnode, context, opts, inner, isSvgMode, selectValue) {
291293
}
292294

293295
s = `<${nodeName}${s}>`;
294-
if (String(nodeName).match(/[\s\n\\/='"\0<>]/))
296+
if (UNSAFE_NAME.test(String(nodeName)))
295297
throw new Error(`${nodeName} is not a valid HTML tag name in ${s}`);
296298

297299
let isVoid =
298-
String(nodeName).match(VOID_ELEMENTS) ||
299-
(opts.voidElements && String(nodeName).match(opts.voidElements));
300+
VOID_ELEMENTS.test(String(nodeName)) ||
301+
(opts.voidElements && opts.voidElements.test(String(nodeName)));
300302
let pieces = [];
301303

302304
let children;

src/util.js

+24-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,20 @@
1+
/**
2+
* @template T
3+
* @param {T} fn
4+
* @returns {T}
5+
*/
6+
function memoize(fn) {
7+
const cache = new Map();
8+
return (arg) => {
9+
let res = cache.get(arg);
10+
if (!res) {
11+
res = fn(arg);
12+
cache.set(arg, res);
13+
}
14+
return res;
15+
};
16+
}
17+
118
// DOM properties that should NOT have "px" added when numeric
219
export const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|^--/i;
320

@@ -9,10 +26,15 @@ const tagsToReplace = {
926
'"': '&quot;'
1027
};
1128
const replaceTag = (tag) => tagsToReplace[tag] || tag;
12-
export function encodeEntities(s) {
29+
30+
/**
31+
* @param {any} s
32+
* @returns {string}
33+
*/
34+
export const encodeEntities = memoize((s) => {
1335
if (typeof s !== 'string') s = String(s);
1436
return s.replace(HTML_ENTITY_REG, replaceTag);
15-
}
37+
});
1638

1739
export let indent = (s, char) =>
1840
String(s).replace(/(\n+)/g, '$1' + (char || '\t'));

0 commit comments

Comments
 (0)