blob: b4b8b65b4c0b353c2d0084a1fbb15d21477c506d [file] [log] [blame]
Tim van der Lippefdbd42e2020-04-07 14:14:361'use strict';
2
Nikolay Vitkovd76576c2024-12-02 14:10:153var isInteger = require('../helpers/isInteger');
Tim van der Lippe2c891972021-07-29 15:22:504var isLeadingSurrogate = require('../helpers/isLeadingSurrogate');
5var isTrailingSurrogate = require('../helpers/isTrailingSurrogate');
Nikolay Vitkovd76576c2024-12-02 14:10:156var MAX_SAFE_INTEGER = require('../helpers/maxSafeInteger');
Tim van der Lippefdbd42e2020-04-07 14:14:367
Nikolay Vitkovd76576c2024-12-02 14:10:158var $TypeError = require('es-errors/type');
Tim van der Lippefdbd42e2020-04-07 14:14:369
Tim van der Lippe2c891972021-07-29 15:22:5010var $charCodeAt = require('call-bind/callBound')('String.prototype.charCodeAt');
Tim van der Lippefdbd42e2020-04-07 14:14:3611
Nikolay Vitkovd76576c2024-12-02 14:10:1512// https://262.ecma-international.org/6.0/#sec-advancestringindex
Tim van der Lippefdbd42e2020-04-07 14:14:3613
14module.exports = function AdvanceStringIndex(S, index, unicode) {
Nikolay Vitkovd76576c2024-12-02 14:10:1515 if (typeof S !== 'string') {
Tim van der Lippefdbd42e2020-04-07 14:14:3616 throw new $TypeError('Assertion failed: `S` must be a String');
17 }
Nikolay Vitkovd76576c2024-12-02 14:10:1518 if (!isInteger(index) || index < 0 || index > MAX_SAFE_INTEGER) {
Tim van der Lippefdbd42e2020-04-07 14:14:3619 throw new $TypeError('Assertion failed: `length` must be an integer >= 0 and <= 2**53');
20 }
Nikolay Vitkovd76576c2024-12-02 14:10:1521 if (typeof unicode !== 'boolean') {
Tim van der Lippefdbd42e2020-04-07 14:14:3622 throw new $TypeError('Assertion failed: `unicode` must be a Boolean');
23 }
24 if (!unicode) {
25 return index + 1;
26 }
27 var length = S.length;
28 if ((index + 1) >= length) {
29 return index + 1;
30 }
31
32 var first = $charCodeAt(S, index);
Tim van der Lippe2c891972021-07-29 15:22:5033 if (!isLeadingSurrogate(first)) {
Tim van der Lippefdbd42e2020-04-07 14:14:3634 return index + 1;
35 }
36
37 var second = $charCodeAt(S, index + 1);
Tim van der Lippe2c891972021-07-29 15:22:5038 if (!isTrailingSurrogate(second)) {
Tim van der Lippefdbd42e2020-04-07 14:14:3639 return index + 1;
40 }
41
42 return index + 2;
43};