string-multibyte.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536
  1. var uncurryThis = require('../internals/function-uncurry-this');
  2. var toIntegerOrInfinity = require('../internals/to-integer-or-infinity');
  3. var toString = require('../internals/to-string');
  4. var requireObjectCoercible = require('../internals/require-object-coercible');
  5. var charAt = uncurryThis(''.charAt);
  6. var charCodeAt = uncurryThis(''.charCodeAt);
  7. var stringSlice = uncurryThis(''.slice);
  8. var createMethod = function (CONVERT_TO_STRING) {
  9. return function ($this, pos) {
  10. var S = toString(requireObjectCoercible($this));
  11. var position = toIntegerOrInfinity(pos);
  12. var size = S.length;
  13. var first, second;
  14. if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
  15. first = charCodeAt(S, position);
  16. return first < 0xD800 || first > 0xDBFF || position + 1 === size
  17. || (second = charCodeAt(S, position + 1)) < 0xDC00 || second > 0xDFFF
  18. ? CONVERT_TO_STRING
  19. ? charAt(S, position)
  20. : first
  21. : CONVERT_TO_STRING
  22. ? stringSlice(S, position, position + 2)
  23. : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
  24. };
  25. };
  26. module.exports = {
  27. // `String.prototype.codePointAt` method
  28. // https://tc39.es/ecma262/#sec-string.prototype.codepointat
  29. codeAt: createMethod(false),
  30. // `String.prototype.at` method
  31. // https://github.com/mathiasbynens/String.prototype.at
  32. charAt: createMethod(true)
  33. };