We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent ad4e7fa commit 15b1527Copy full SHA for 15b1527
TypeScript/compact-object.ts
@@ -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