Skip to content

Commit adf1c59

Browse files
committed
minor fixes
1 parent e61ac7b commit adf1c59

File tree

1 file changed

+43
-25
lines changed

1 file changed

+43
-25
lines changed

text-utils/capitalizeKeys.js

Lines changed: 43 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,48 @@
1-
2-
function capitalizeKeys(obj, mapper, seen = new WeakSet()) {
3-
if (Array.isArray(obj)) {
4-
return obj.map(item => capitalizeKeys(item, mapper, seen));
5-
}
6-
7-
if (Object.prototype.toString.call(obj) !== '[object Object]') {
8-
return obj;
9-
}
10-
11-
if (seen.has(obj)) {
12-
throw new Error("Circular reference detected");
1+
function capitalizeKeys(obj, mapper) {
2+
const seen = new WeakSet();
3+
const stack = [{ input: obj, output: Array.isArray(obj) ? [] : {} }];
4+
const rootOutput = stack[0].output;
5+
6+
while (stack.length > 0) {
7+
const { input, output } = stack.pop();
8+
9+
if (seen.has(input)) {
10+
console.error("Circular reference in capitalizeKeys", obj);
11+
throw new Error("Circular reference detected");
12+
}
13+
seen.add(input);
14+
15+
if (Array.isArray(input)) {
16+
input.forEach((item, index) => {
17+
if (Array.isArray(item)) {
18+
output[index] = [];
19+
stack.push({ input: item, output: output[index] });
20+
} else if (typeof item === 'object' && item !== null) {
21+
output[index] = {};
22+
stack.push({ input: item, output: output[index] });
23+
} else {
24+
output[index] = item;
25+
}
26+
});
27+
} else if (typeof input === 'object' && input !== null) {
28+
Object.entries(input).forEach(([key, value]) => {
29+
let keyCapitalized = key.replace(/_(\w)/g, (_, letter) => letter.toUpperCase());
30+
if (mapper) keyCapitalized = mapper(keyCapitalized);
31+
32+
if (Array.isArray(value)) {
33+
output[keyCapitalized] = [];
34+
stack.push({ input: value, output: output[keyCapitalized] });
35+
} else if (typeof value === 'object' && value !== null) {
36+
output[keyCapitalized] = {};
37+
stack.push({ input: value, output: output[keyCapitalized] });
38+
} else {
39+
output[keyCapitalized] = value;
40+
}
41+
});
42+
}
1343
}
1444

15-
seen.add(obj); // Mark the object as visited.
16-
17-
let output = {};
18-
19-
for (let key in obj) {
20-
let keyCapitalized = key.replace(/_(\w)/g, (match, letter) => letter.toUpperCase());
21-
if (mapper) keyCapitalized = mapper(keyCapitalized);
22-
output[keyCapitalized] = capitalizeKeys(obj[key], mapper, seen);
23-
}
24-
25-
seen.delete(obj); // Remove from `seen` after processing to allow for reuse in non-circular parts.
26-
27-
return output;
45+
return rootOutput;
2846
}
2947

3048
module.exports = capitalizeKeys;

0 commit comments

Comments
 (0)