at.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  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, cuFirst, cuSecond, nextPos, len;
  8. pos = toInteger(pos);
  9. // Account for out-of-bounds indices
  10. // The odd lower bound is because the ToInteger operation is
  11. // going to round `n` to `0` for `-1 < n <= 0`.
  12. if (pos <= -1 || pos >= size) return "";
  13. // Second half of `ToInteger`
  14. // eslint-disable-next-line no-bitwise
  15. 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 (
  21. // Check if it’s the start of a surrogate pair
  22. cuFirst >= 0xd800 &&
  23. cuFirst <= 0xdbff && // High surrogate
  24. size > nextPos // There is a next code unit
  25. ) {
  26. cuSecond = str.charCodeAt(nextPos);
  27. if (cuSecond >= 0xdc00 && cuSecond <= 0xdfff) len = 2; // Low surrogate
  28. }
  29. return str.slice(pos, pos + len);
  30. };