UNPKG

1.15 kBJavaScriptView Raw
1var toInteger = require('../internals/to-integer');
2var requireObjectCoercible = require('../internals/require-object-coercible');
3
4// `String.prototype.{ codePointAt, at }` methods implementation
5var createMethod = function (CONVERT_TO_STRING) {
6 return function ($this, pos) {
7 var S = String(requireObjectCoercible($this));
8 var position = toInteger(pos);
9 var size = S.length;
10 var first, second;
11 if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
12 first = S.charCodeAt(position);
13 return first < 0xD800 || first > 0xDBFF || position + 1 === size
14 || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF
15 ? CONVERT_TO_STRING ? S.charAt(position) : first
16 : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
17 };
18};
19
20module.exports = {
21 // `String.prototype.codePointAt` method
22 // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat
23 codeAt: createMethod(false),
24 // `String.prototype.at` method
25 // https://github.com/mathiasbynens/String.prototype.at
26 charAt: createMethod(true)
27};