* Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. *
(string)
| 111 | * @returns {Array} The new array of code points. |
| 112 | */ |
| 113 | function ucs2decode(string) { |
| 114 | const output = []; |
| 115 | let counter = 0; |
| 116 | const length = string.length; |
| 117 | while (counter < length) { |
| 118 | const value = string.charCodeAt(counter++); |
| 119 | if (value >= 0xD800 && value <= 0xDBFF && counter < length) { |
| 120 | // It's a high surrogate, and there is a next character. |
| 121 | const extra = string.charCodeAt(counter++); |
| 122 | if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. |
| 123 | output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); |
| 124 | } else { |
| 125 | // It's an unmatched surrogate; only append this code unit, in case the |
| 126 | // next code unit is the high surrogate of a surrogate pair. |
| 127 | output.push(value); |
| 128 | counter--; |
| 129 | } |
| 130 | } else { |
| 131 | output.push(value); |
| 132 | } |
| 133 | } |
| 134 | return output; |
| 135 | } |
| 136 | |
| 137 | /** |
| 138 | * Creates a string based on an array of numeric code points. |