at.js 1.0 KB

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