You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AdvanceStringIndex.js 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. var GetIntrinsic = require('../GetIntrinsic');
  3. var IsInteger = require('./IsInteger');
  4. var Type = require('./Type');
  5. var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger');
  6. var $TypeError = GetIntrinsic('%TypeError%');
  7. var $charCodeAt = require('../helpers/callBound')('String.prototype.charCodeAt');
  8. // https://ecma-international.org/ecma-262/6.0/#sec-advancestringindex
  9. module.exports = function AdvanceStringIndex(S, index, unicode) {
  10. if (Type(S) !== 'String') {
  11. throw new $TypeError('Assertion failed: `S` must be a String');
  12. }
  13. if (!IsInteger(index) || index < 0 || index > MAX_SAFE_INTEGER) {
  14. throw new $TypeError('Assertion failed: `length` must be an integer >= 0 and <= 2**53');
  15. }
  16. if (Type(unicode) !== 'Boolean') {
  17. throw new $TypeError('Assertion failed: `unicode` must be a Boolean');
  18. }
  19. if (!unicode) {
  20. return index + 1;
  21. }
  22. var length = S.length;
  23. if ((index + 1) >= length) {
  24. return index + 1;
  25. }
  26. var first = $charCodeAt(S, index);
  27. if (first < 0xD800 || first > 0xDBFF) {
  28. return index + 1;
  29. }
  30. var second = $charCodeAt(S, index + 1);
  31. if (second < 0xDC00 || second > 0xDFFF) {
  32. return index + 1;
  33. }
  34. return index + 2;
  35. };