From 799bc6f8037606bbe5c39c2bb06be74a7ec25f21 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sat, 3 Jun 2023 23:27:12 +0200 Subject: [PATCH] =?UTF-8?q?problems(js):=20add=20=E2=80=9C2633.=20Convert?= =?UTF-8?q?=20Object=20to=20JSON=20String=E2=80=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- problems/js/convert-object-to-json-string.js | 25 ++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 problems/js/convert-object-to-json-string.js diff --git a/problems/js/convert-object-to-json-string.js b/problems/js/convert-object-to-json-string.js new file mode 100644 index 0000000..e3f6286 --- /dev/null +++ b/problems/js/convert-object-to-json-string.js @@ -0,0 +1,25 @@ +/** + * @param {any} object + * @return {string} + */ +var jsonStringify = function(object) { + switch (typeof object) { + case 'boolean': + case 'number': + return `${object}`; + case 'string': + return `"${object}"`; + case 'object': + if (Array.isArray(object)) { + return `[${object.map(jsonStringify).join(',')}]`; + } + + if (object) { + let nested = Object.keys(object).map(key => `"${key}":${jsonStringify(object[key])}`); + return `{${nested.join(',')}}`; + } + return 'null'; + default: + return ''; + } +};