UnicodeUtils.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @typechecks
  8. */
  9. /**
  10. * Unicode-enabled replacesments for basic String functions.
  11. *
  12. * All the functions in this module assume that the input string is a valid
  13. * UTF-16 encoding of a Unicode sequence. If it's not the case, the behavior
  14. * will be undefined.
  15. *
  16. * WARNING: Since this module is typechecks-enforced, you may find new bugs
  17. * when replacing normal String functions with ones provided here.
  18. */
  19. 'use strict';
  20. var invariant = require("./invariant"); // These two ranges are consecutive so anything in [HIGH_START, LOW_END] is a
  21. // surrogate code unit.
  22. var SURROGATE_HIGH_START = 0xD800;
  23. var SURROGATE_HIGH_END = 0xDBFF;
  24. var SURROGATE_LOW_START = 0xDC00;
  25. var SURROGATE_LOW_END = 0xDFFF;
  26. var SURROGATE_UNITS_REGEX = /[\uD800-\uDFFF]/;
  27. /**
  28. * @param {number} codeUnit A Unicode code-unit, in range [0, 0x10FFFF]
  29. * @return {boolean} Whether code-unit is in a surrogate (hi/low) range
  30. */
  31. function isCodeUnitInSurrogateRange(codeUnit) {
  32. return SURROGATE_HIGH_START <= codeUnit && codeUnit <= SURROGATE_LOW_END;
  33. }
  34. /**
  35. * Returns whether the two characters starting at `index` form a surrogate pair.
  36. * For example, given the string s = "\uD83D\uDE0A", (s, 0) returns true and
  37. * (s, 1) returns false.
  38. *
  39. * @param {string} str
  40. * @param {number} index
  41. * @return {boolean}
  42. */
  43. function isSurrogatePair(str, index) {
  44. !(0 <= index && index < str.length) ? process.env.NODE_ENV !== "production" ? invariant(false, 'isSurrogatePair: Invalid index %s for string length %s.', index, str.length) : invariant(false) : void 0;
  45. if (index + 1 === str.length) {
  46. return false;
  47. }
  48. var first = str.charCodeAt(index);
  49. var second = str.charCodeAt(index + 1);
  50. return SURROGATE_HIGH_START <= first && first <= SURROGATE_HIGH_END && SURROGATE_LOW_START <= second && second <= SURROGATE_LOW_END;
  51. }
  52. /**
  53. * @param {string} str Non-empty string
  54. * @return {boolean} True if the input includes any surrogate code units
  55. */
  56. function hasSurrogateUnit(str) {
  57. return SURROGATE_UNITS_REGEX.test(str);
  58. }
  59. /**
  60. * Return the length of the original Unicode character at given position in the
  61. * String by looking into the UTF-16 code unit; that is equal to 1 for any
  62. * non-surrogate characters in BMP ([U+0000..U+D7FF] and [U+E000, U+FFFF]); and
  63. * returns 2 for the hi/low surrogates ([U+D800..U+DFFF]), which are in fact
  64. * representing non-BMP characters ([U+10000..U+10FFFF]).
  65. *
  66. * Examples:
  67. * - '\u0020' => 1
  68. * - '\u3020' => 1
  69. * - '\uD835' => 2
  70. * - '\uD835\uDDEF' => 2
  71. * - '\uDDEF' => 2
  72. *
  73. * @param {string} str Non-empty string
  74. * @param {number} pos Position in the string to look for one code unit
  75. * @return {number} Number 1 or 2
  76. */
  77. function getUTF16Length(str, pos) {
  78. return 1 + isCodeUnitInSurrogateRange(str.charCodeAt(pos));
  79. }
  80. /**
  81. * Fully Unicode-enabled replacement for String#length
  82. *
  83. * @param {string} str Valid Unicode string
  84. * @return {number} The number of Unicode characters in the string
  85. */
  86. function strlen(str) {
  87. // Call the native functions if there's no surrogate char
  88. if (!hasSurrogateUnit(str)) {
  89. return str.length;
  90. }
  91. var len = 0;
  92. for (var pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) {
  93. len++;
  94. }
  95. return len;
  96. }
  97. /**
  98. * Fully Unicode-enabled replacement for String#substr()
  99. *
  100. * @param {string} str Valid Unicode string
  101. * @param {number} start Location in Unicode sequence to begin extracting
  102. * @param {?number} length The number of Unicode characters to extract
  103. * (default: to the end of the string)
  104. * @return {string} Extracted sub-string
  105. */
  106. function substr(str, start, length) {
  107. start = start || 0;
  108. length = length === undefined ? Infinity : length || 0; // Call the native functions if there's no surrogate char
  109. if (!hasSurrogateUnit(str)) {
  110. return str.substr(start, length);
  111. } // Obvious cases
  112. var size = str.length;
  113. if (size <= 0 || start > size || length <= 0) {
  114. return '';
  115. } // Find the actual starting position
  116. var posA = 0;
  117. if (start > 0) {
  118. for (; start > 0 && posA < size; start--) {
  119. posA += getUTF16Length(str, posA);
  120. }
  121. if (posA >= size) {
  122. return '';
  123. }
  124. } else if (start < 0) {
  125. for (posA = size; start < 0 && 0 < posA; start++) {
  126. posA -= getUTF16Length(str, posA - 1);
  127. }
  128. if (posA < 0) {
  129. posA = 0;
  130. }
  131. } // Find the actual ending position
  132. var posB = size;
  133. if (length < size) {
  134. for (posB = posA; length > 0 && posB < size; length--) {
  135. posB += getUTF16Length(str, posB);
  136. }
  137. }
  138. return str.substring(posA, posB);
  139. }
  140. /**
  141. * Fully Unicode-enabled replacement for String#substring()
  142. *
  143. * @param {string} str Valid Unicode string
  144. * @param {number} start Location in Unicode sequence to begin extracting
  145. * @param {?number} end Location in Unicode sequence to end extracting
  146. * (default: end of the string)
  147. * @return {string} Extracted sub-string
  148. */
  149. function substring(str, start, end) {
  150. start = start || 0;
  151. end = end === undefined ? Infinity : end || 0;
  152. if (start < 0) {
  153. start = 0;
  154. }
  155. if (end < 0) {
  156. end = 0;
  157. }
  158. var length = Math.abs(end - start);
  159. start = start < end ? start : end;
  160. return substr(str, start, length);
  161. }
  162. /**
  163. * Get a list of Unicode code-points from a String
  164. *
  165. * @param {string} str Valid Unicode string
  166. * @return {array<number>} A list of code-points in [0..0x10FFFF]
  167. */
  168. function getCodePoints(str) {
  169. var codePoints = [];
  170. for (var pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) {
  171. codePoints.push(str.codePointAt(pos));
  172. }
  173. return codePoints;
  174. }
  175. var UnicodeUtils = {
  176. getCodePoints: getCodePoints,
  177. getUTF16Length: getUTF16Length,
  178. hasSurrogateUnit: hasSurrogateUnit,
  179. isCodeUnitInSurrogateRange: isCodeUnitInSurrogateRange,
  180. isSurrogatePair: isSurrogatePair,
  181. strlen: strlen,
  182. substring: substring,
  183. substr: substr
  184. };
  185. module.exports = UnicodeUtils;