MCPcopy Create free account
hub / github.com/cryptii/cryptii / codePointsFromString

Method codePointsFromString

src/TextEncoder.js:83–122  ·  view source on GitHub ↗

* 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

(string)

Source from the content-addressed store, hash-verified

81 * @returns {number[]} Array of Unicode code points
82 */
83 static codePointsFromString (string) {
84 // In the worst case every string code unit needs to be translated to
85 // a single code point each
86 // Create a fixed size array that gets sliced at the end
87 const length = string.length
88 const codePoints = new Array(length)
89
90 let codeUnit, nextCodeUnit
91 let j = 0
92 let i = 0
93
94 while (i < length) {
95 codeUnit = string.charCodeAt(i++)
96
97 if (codeUnit >= 0xD800 && codeUnit <= 0xDBFF && i < length) {
98 // Identified a high surrogate
99 nextCodeUnit = string.charCodeAt(i++)
100
101 // There is a next character
102 if ((nextCodeUnit & 0xFC00) === 0xDC00) {
103 // Low surrogate
104 codePoints[j++] =
105 ((codeUnit & 0x3FF) << 10) +
106 (nextCodeUnit & 0x3FF) +
107 0x10000
108 } else {
109 // Unmatched surrogate; Only append this code unit, in case
110 // the next code unit is the high surrogate of a surrogate pair
111 codePoints[j++] = codeUnit
112 i--
113 }
114 } else {
115 // Identified BMP character
116 codePoints[j++] = codeUnit
117 }
118 }
119
120 // Slice the fixed size array to the portion actually in use
121 return codePoints.slice(0, j)
122 }
123
124 /**
125 * Encodes Unicode code points to bytes using given encoding.

Callers 4

TextEncoder.jsFile · 0.80
getCodePointsMethod · 0.80
indexOfMethod · 0.80

Calls

no outgoing calls

Tested by

no test coverage detected