-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy path4-serialize.js
More file actions
33 lines (29 loc) · 708 Bytes
/
Copy path4-serialize.js
File metadata and controls
33 lines (29 loc) · 708 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
27
28
29
30
31
32
33
'use strict';
const serialize = (obj) => {
const type = typeof obj;
if (obj === null) return 'null';
else if (type === 'string') return `'${obj}'`;
else if (type === 'number') return obj.toString();
else if (type === 'boolean') return obj.toString();
else if (type !== 'object') return obj.toString();
else if (Array.isArray(obj)) {
return `[${obj}]`;
} else {
let s = '{';
for (const key in obj) {
const value = obj[key];
if (s.length > 1) s += ',';
s += key + ':' + serialize(value);
}
return s + '}';
}
};
// Usage
const obj1 = {
field: 'Value',
subObject: {
arr: [7, 10, 2, 5],
fn: (x) => x / 2
}
};
console.log(serialize(obj1));