diff --git a/src/util.js b/src/util.js index 679a02e2..eee3d35d 100644 --- a/src/util.js +++ b/src/util.js @@ -1,3 +1,20 @@ +/** + * @template T + * @param {T} fn + * @returns {T} + */ +function memoize(fn) { + const cache = new Map(); + return (arg) => { + let res = cache.get(arg); + if (!res) { + res = fn(arg); + cache.set(arg, res); + } + return res; + }; +} + // DOM properties that should NOT have "px" added when numeric export const IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|^--/i; @@ -9,10 +26,15 @@ const tagsToReplace = { '"': '"' }; const replaceTag = (tag) => tagsToReplace[tag] || tag; -export function encodeEntities(s) { + +/** + * @param {any} s + * @returns {string} + */ +export const encodeEntities = memoize((s) => { if (typeof s !== 'string') s = String(s); return s.replace(HTML_ENTITY_REG, replaceTag); -} +}); export let indent = (s, char) => String(s).replace(/(\n+)/g, '$1' + (char || '\t'));