AdvanceStringIndex.js 917 B

12345678910111213141516171819202122232425262728293031
  1. 'use strict';
  2. var CodePointAt = require('./CodePointAt');
  3. var isInteger = require('../helpers/isInteger');
  4. var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger');
  5. var $TypeError = require('es-errors/type');
  6. // https://262.ecma-international.org/12.0/#sec-advancestringindex
  7. module.exports = function AdvanceStringIndex(S, index, unicode) {
  8. if (typeof S !== 'string') {
  9. throw new $TypeError('Assertion failed: `S` must be a String');
  10. }
  11. if (!isInteger(index) || index < 0 || index > MAX_SAFE_INTEGER) {
  12. throw new $TypeError('Assertion failed: `length` must be an integer >= 0 and <= 2**53');
  13. }
  14. if (typeof unicode !== 'boolean') {
  15. throw new $TypeError('Assertion failed: `unicode` must be a Boolean');
  16. }
  17. if (!unicode) {
  18. return index + 1;
  19. }
  20. var length = S.length;
  21. if ((index + 1) >= length) {
  22. return index + 1;
  23. }
  24. var cp = CodePointAt(S, index);
  25. return index + cp['[[CodeUnitCount]]'];
  26. };