-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.stringify.js
More file actions
27 lines (21 loc) · 868 Bytes
/
json.stringify.js
File metadata and controls
27 lines (21 loc) · 868 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// ref: https://bigfrontend.dev/problem/implement-JSON-stringify
function stringify(data) {
if ([null, undefined].includes(data)) return 'null';
if (typeof data === 'string') return `"${data}"`;
if (['number', 'boolean'].includes(typeof data)) return `${data}`;
if (typeof data === "object") {
if (Array.isArray(data)) {
let out = data.reduce((acc, i) => acc + (stringify(i) + ","), "");
out = out.substring(0, out.length - 1);
return "[" + out + "]";
} else {
let out = Object.keys(data).reduce((acc, key) => {
const val = data[key];
if (val !== undefined) acc += `"${key}":${stringify(val)},`;
return acc;
}, "");
out = out.substring(0, out.length - 1);
return "{" + out + "}";
}
}
}