From 2b21ae8f8eacef8fa5dd1c962bf5eb72d51f3910 Mon Sep 17 00:00:00 2001 From: shengxinjing <316783812@qq.com> Date: Sat, 2 May 2020 11:17:00 +0800 Subject: [PATCH] refactor(shared): replace switch with config in escapeHtml --- packages/shared/src/escapeHtml.ts | 42 +++++++++++++------------------ 1 file changed, 17 insertions(+), 25 deletions(-) diff --git a/packages/shared/src/escapeHtml.ts b/packages/shared/src/escapeHtml.ts index 4a6435e6a51..8b849233ca7 100644 --- a/packages/shared/src/escapeHtml.ts +++ b/packages/shared/src/escapeHtml.ts @@ -12,33 +12,25 @@ export function escapeHtml(string: unknown) { let escaped: string let index: number let lastIndex = 0 + const codeToEscapes:any = { + 34:'"', // " + 38:'&', // & + 39:''', // ' + 60:'<', // < + 62:'>' // > + } for (index = match.index; index < str.length; index++) { - switch (str.charCodeAt(index)) { - case 34: // " - escaped = '"' - break - case 38: // & - escaped = '&' - break - case 39: // ' - escaped = ''' - break - case 60: // < - escaped = '<' - break - case 62: // > - escaped = '>' - break - default: - continue - } - - if (lastIndex !== index) { - html += str.substring(lastIndex, index) + const code = str.charCodeAt(index) + + if(codeToEscapes[code]){ + escaped = codeToEscapes[code] + if (lastIndex !== index) { + html += str.substring(lastIndex, index) + } + + lastIndex = index + 1 + html += escaped } - - lastIndex = index + 1 - html += escaped } return lastIndex !== index ? html + str.substring(lastIndex, index) : html