Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit aa2eb7d

Browse files
mayunhaiPanJiaChen
authored andcommitted
perf[utils.js]: refactor byteLength function (PanJiaChen#1650)
1 parent 6255f54 commit aa2eb7d

File tree

1 file changed

+10
-11
lines changed

1 file changed

+10
-11
lines changed

src/utils/index.js

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -91,20 +91,19 @@ export function getQueryObject(url) {
9191
}
9292

9393
/**
94-
*get getByteLen
95-
* @param {Sting} val input value
94+
* @param {Sting} input value
9695
* @returns {number} output value
9796
*/
98-
export function getByteLen(val) {
99-
let len = 0
100-
for (let i = 0; i < val.length; i++) {
101-
if (val[i].match(/[^\x00-\xff]/gi) != null) {
102-
len += 1
103-
} else {
104-
len += 0.5
105-
}
97+
export function byteLength(str) {
98+
// returns the byte length of an utf8 string
99+
let s = str.length
100+
for (var i = str.length - 1; i >= 0; i--) {
101+
const code = str.charCodeAt(i)
102+
if (code > 0x7f && code <= 0x7ff) s++
103+
else if (code > 0x7ff && code <= 0xffff) s += 2
104+
if (code >= 0xDC00 && code <= 0xDFFF) i--
106105
}
107-
return Math.floor(len)
106+
return s
108107
}
109108

110109
export function cleanArray(actual) {

0 commit comments

Comments
 (0)