| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | |
| 3 | var GetIntrinsic = require('get-intrinsic'); |
| 4 | |
| 5 | var $TypeError = GetIntrinsic('%TypeError%'); |
| 6 | |
| 7 | var callBound = require('call-bind/callBound'); |
| 8 | var forEach = require('../helpers/forEach'); |
| 9 | |
| 10 | var $charCodeAt = callBound('String.prototype.charCodeAt'); |
| 11 | var $strSplit = callBound('String.prototype.split'); |
| 12 | |
| 13 | var Type = require('./Type'); |
| 14 | var UnicodeEscape = require('./UnicodeEscape'); |
| 15 | |
| 16 | var has = require('has'); |
| 17 | |
| 18 | // https://262.ecma-international.org/9.0/#sec-quotejsonstring |
| 19 | |
| 20 | var escapes = { |
| 21 | '\u0008': '\\b', |
| 22 | '\u0009': '\\t', |
| 23 | '\u000A': '\\n', |
| 24 | '\u000C': '\\f', |
| 25 | '\u000D': '\\r', |
| 26 | '\u0022': '\\"', |
| 27 | '\u005c': '\\\\' |
| 28 | }; |
| 29 | |
| 30 | module.exports = function QuoteJSONString(value) { |
| 31 | if (Type(value) !== 'String') { |
| 32 | throw new $TypeError('Assertion failed: `value` must be a String'); |
| 33 | } |
| 34 | var product = '"'; |
| 35 | if (value) { |
| 36 | forEach($strSplit(value), function (C) { |
| 37 | if (has(escapes, C)) { |
| 38 | product += escapes[C]; |
| 39 | } else if ($charCodeAt(C, 0) < 0x20) { |
| 40 | product += UnicodeEscape(C); |
| 41 | } else { |
| 42 | product += C; |
| 43 | } |
| 44 | }); |
| 45 | } |
| 46 | product += '"'; |
| 47 | return product; |
| 48 | }; |