AdvanceStringIndex.js 983 B

12345678910111213141516171819202122232425262728293031323334
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var CodePointAt = require('./CodePointAt');
  4. var IsInteger = require('./IsInteger');
  5. var Type = require('./Type');
  6. var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger');
  7. var $TypeError = GetIntrinsic('%TypeError%');
  8. // https://262.ecma-international.org/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 cp = CodePointAt(S, index);
  27. return index + cp['[[CodeUnitCount]]'];
  28. };