GetStringIndex.js 858 B

123456789101112131415161718192021222324252627282930
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var callBound = require('call-bind/callBound');
  4. var $TypeError = GetIntrinsic('%TypeError%');
  5. var IsIntegralNumber = require('./IsIntegralNumber');
  6. var StringToCodePoints = require('./StringToCodePoints');
  7. var Type = require('./Type');
  8. var $indexOf = callBound('String.prototype.indexOf');
  9. // https://ecma-international.org/ecma-262/13.0/#sec-getstringindex
  10. module.exports = function GetStringIndex(S, e) {
  11. if (Type(S) !== 'String') {
  12. throw new $TypeError('Assertion failed: `S` must be a String');
  13. }
  14. if (!IsIntegralNumber(e) || e < 0) {
  15. throw new $TypeError('Assertion failed: `e` must be a non-negative integer');
  16. }
  17. if (S === '') {
  18. return 0;
  19. }
  20. var codepoints = StringToCodePoints(S);
  21. var eUTF = e >= codepoints.length ? S.length : $indexOf(S, codepoints[e]);
  22. return eUTF;
  23. };