GetStringIndex.js 842 B

12345678910111213141516171819202122232425262728293031
  1. 'use strict';
  2. var GetIntrinsic = require('get-intrinsic');
  3. var callBound = require('call-bind/callBound');
  4. var $TypeError = GetIntrinsic('%TypeError%');
  5. var StringToCodePoints = require('./StringToCodePoints');
  6. var Type = require('./Type');
  7. var isInteger = require('../helpers/isInteger');
  8. var $indexOf = callBound('String.prototype.indexOf');
  9. // https://262.ecma-international.org/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 (!isInteger(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. };