AdvanceStringIndex.js 936 B

123456789101112131415161718192021222324252627282930
  1. 'use strict';
  2. var CodePointAt = require('./CodePointAt');
  3. var $TypeError = require('es-errors/type');
  4. var isInteger = require('math-intrinsics/isInteger');
  5. var MAX_SAFE_INTEGER = require('math-intrinsics/constants/maxSafeInteger');
  6. // https://262.ecma-international.org/11.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. };