es.json.stringify.js 1.1 KB

1234567891011121314151617181920212223242526272829303132
  1. var $ = require('../internals/export');
  2. var getBuiltIn = require('../internals/get-built-in');
  3. var fails = require('../internals/fails');
  4. var $stringify = getBuiltIn('JSON', 'stringify');
  5. var re = /[\uD800-\uDFFF]/g;
  6. var low = /^[\uD800-\uDBFF]$/;
  7. var hi = /^[\uDC00-\uDFFF]$/;
  8. var fix = function (match, offset, string) {
  9. var prev = string.charAt(offset - 1);
  10. var next = string.charAt(offset + 1);
  11. if ((low.test(match) && !hi.test(next)) || (hi.test(match) && !low.test(prev))) {
  12. return '\\u' + match.charCodeAt(0).toString(16);
  13. } return match;
  14. };
  15. var FORCED = fails(function () {
  16. return $stringify('\uDF06\uD834') !== '"\\udf06\\ud834"'
  17. || $stringify('\uDEAD') !== '"\\udead"';
  18. });
  19. if ($stringify) {
  20. // https://github.com/tc39/proposal-well-formed-stringify
  21. $({ target: 'JSON', stat: true, forced: FORCED }, {
  22. // eslint-disable-next-line no-unused-vars
  23. stringify: function stringify(it, replacer, space) {
  24. var result = $stringify.apply(null, arguments);
  25. return typeof result == 'string' ? result.replace(re, fix) : result;
  26. }
  27. });
  28. }