From f2144d503288d9cb3bd1fbb1c18a7bc41d81fce1 Mon Sep 17 00:00:00 2001 From: chee Date: Fri, 17 May 2019 23:38:53 +0100 Subject: [PATCH] =?UTF-8?q?Add=20na=C3=AFve=20escaping=20to=20stringify?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- code/stringify.js | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/code/stringify.js b/code/stringify.js index 82cbd63..2e9c948 100644 --- a/code/stringify.js +++ b/code/stringify.js @@ -1,19 +1,25 @@ -module.exports = function stringify (object) { +function escape (string) { + return string + .replace(/\\/g, '\\\\') + .replace(/"/g, '\\"') +} + +module.exports = function stringify (thing) { let result = '' - if (Array.isArray(object)) { + if (Array.isArray(thing)) { result += '( ' - result += object.map(stringify).join(', ') + result += thing.map(stringify).join(', ') result += ' )' - } else if (object.constructor === Object) { + } else if (thing.constructor === Object) { result += '{ ' - for (const key in object) { + for (const key in thing) { result += `"${key}" = ` - result += stringify(object[key]) + result += stringify(thing[key]) result += '; ' } result += '}' } else { - result += `"${object.toString()}"` + result += `"${escape(thing.toString())}"` } return result }