]> git.r.bdr.sh - rbdr/dotfiles/blob
77bd251ac4f1ae55b8e6b94e0c46b151a612a56d
[rbdr/dotfiles] /
1 // Based on: https://github.com/mathiasbynens/String.prototype.at
2 // Thanks @mathiasbynens !
3
4 'use strict';
5
6 var toInteger = require('../../number/to-integer')
7 , validValue = require('../../object/valid-value');
8
9 module.exports = function (pos) {
10 var str = String(validValue(this)), size = str.length
11 , cuFirst, cuSecond, nextPos, len;
12 pos = toInteger(pos);
13
14 // Account for out-of-bounds indices
15 // The odd lower bound is because the ToInteger operation is
16 // going to round `n` to `0` for `-1 < n <= 0`.
17 if (pos <= -1 || pos >= size) return '';
18
19 // Second half of `ToInteger`
20 pos = pos | 0;
21 // Get the first code unit and code unit value
22 cuFirst = str.charCodeAt(pos);
23 nextPos = pos + 1;
24 len = 1;
25 if ( // check if it’s the start of a surrogate pair
26 (cuFirst >= 0xD800) && (cuFirst <= 0xDBFF) && // high surrogate
27 (size > nextPos) // there is a next code unit
28 ) {
29 cuSecond = str.charCodeAt(nextPos);
30 if (cuSecond >= 0xDC00 && cuSecond <= 0xDFFF) len = 2; // low surrogate
31 }
32 return str.slice(pos, pos + len);
33 };