Skip to content

Commit 15b1527

Browse files
authored
Create compact-object.ts
1 parent ad4e7fa commit 15b1527

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

TypeScript/compact-object.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Time: O(n)
2+
// Space: O(h)
3+
4+
type Obj = Record<any, any>;
5+
6+
// dfs
7+
function compactObject(obj: Obj): Obj {
8+
if (obj === null) {
9+
return null;
10+
}
11+
if (Array.isArray(obj)) {
12+
return obj.filter(Boolean).map(compactObject);
13+
}
14+
if (typeof obj !== "object") {
15+
return obj;
16+
}
17+
return Object.keys(obj).reduce(
18+
(accu, key) => {
19+
accu[key] = compactObject(obj[key]);
20+
if (!Boolean(accu[key])) {
21+
delete accu[key];
22+
}
23+
return accu;
24+
}, {});
25+
};

0 commit comments

Comments
 (0)