esnext.string.to-well-formed.js 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var uncurryThis = require('../internals/function-uncurry-this');
  4. var requireObjectCoercible = require('../internals/require-object-coercible');
  5. var toString = require('../internals/to-string');
  6. var $Array = Array;
  7. var charAt = uncurryThis(''.charAt);
  8. var charCodeAt = uncurryThis(''.charCodeAt);
  9. var join = uncurryThis([].join);
  10. var REPLACEMENT_CHARACTER = '\uFFFD';
  11. // `String.prototype.toWellFormed` method
  12. // https://github.com/tc39/proposal-is-usv-string
  13. $({ target: 'String', proto: true, forced: true }, {
  14. toWellFormed: function toWellFormed() {
  15. var S = toString(requireObjectCoercible(this));
  16. var length = S.length;
  17. var result = $Array(length);
  18. for (var i = 0; i < length; i++) {
  19. var charCode = charCodeAt(S, i);
  20. // single UTF-16 code unit
  21. if ((charCode & 0xF800) != 0xD800) result[i] = charAt(S, i);
  22. // unpaired surrogate
  23. else if (charCode >= 0xDC00 || i + 1 >= length || (charCodeAt(S, i + 1) & 0xFC00) != 0xDC00) result[i] = REPLACEMENT_CHARACTER;
  24. // surrogate pair
  25. else {
  26. result[i] = charAt(S, i);
  27. result[++i] = charAt(S, i);
  28. }
  29. } return join(result, '');
  30. }
  31. });