AdvanceStringIndex.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. var isInteger = require('../helpers/isInteger');
  3. var isLeadingSurrogate = require('../helpers/isLeadingSurrogate');
  4. var isTrailingSurrogate = require('../helpers/isTrailingSurrogate');
  5. var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger');
  6. var $TypeError = require('es-errors/type');
  7. var $charCodeAt = require('call-bind/callBound')('String.prototype.charCodeAt');
  8. // https://262.ecma-international.org/6.0/#sec-advancestringindex
  9. module.exports = function AdvanceStringIndex(S, index, unicode) {
  10. if (typeof 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 (typeof 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 (!isLeadingSurrogate(first)) {
  28. return index + 1;
  29. }
  30. var second = $charCodeAt(S, index + 1);
  31. if (!isTrailingSurrogate(second)) {
  32. return index + 1;
  33. }
  34. return index + 2;
  35. };