1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-10 00:09:06 +01:00

problems(js): add “2633. Convert Object to JSON String”

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-06-03 23:27:12 +02:00
parent 988f8fb927
commit 799bc6f803
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -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 '';
}
};