From aa2eb7d40f1e64bfaf3a0ee1d0dd5a0a6d161dee Mon Sep 17 00:00:00 2001 From: MaYuanhai <414199639@qq.com> Date: Mon, 4 Mar 2019 10:54:58 +0800 Subject: [PATCH] perf[utils.js]: refactor byteLength function (#1650) --- src/utils/index.js | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/utils/index.js b/src/utils/index.js index 1370a423..fbcb4602 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -91,20 +91,19 @@ export function getQueryObject(url) { } /** - *get getByteLen - * @param {Sting} val input value + * @param {Sting} input value * @returns {number} output value */ -export function getByteLen(val) { - let len = 0 - for (let i = 0; i < val.length; i++) { - if (val[i].match(/[^\x00-\xff]/gi) != null) { - len += 1 - } else { - len += 0.5 - } +export function byteLength(str) { + // returns the byte length of an utf8 string + let s = str.length + for (var i = str.length - 1; i >= 0; i--) { + const code = str.charCodeAt(i) + if (code > 0x7f && code <= 0x7ff) s++ + else if (code > 0x7ff && code <= 0xffff) s += 2 + if (code >= 0xDC00 && code <= 0xDFFF) i-- } - return Math.floor(len) + return s } export function cleanArray(actual) {