I trying to copy an object. I want to made it with algorithm Depth-First Search.
JavaScript
x
49
49
1
function dfs(data) {
2
let stack = [];
3
let res = {};
4
5
for (let key in data) {
6
stack.push({ data: data[key], keyData: key });
7
8
while (stack.length !== 0) {
9
const first = stack.shift();
10
11
if (typeof first.data === "object") {
12
for (let key in first.data) {
13
if (typeof first.data[key] === "object") {
14
stack.push({ data: first.data[key], keyData: key });
15
} else {
16
res[first.parentKey] = first.keyData;
17
}
18
}
19
} else {
20
res[first.keyData] = first.data;
21
}
22
}
23
}
24
25
return res;
26
}
27
28
const data = {
29
a: 1,
30
b: 2,
31
c: {
32
d: 3,
33
g: {
34
e: 4,
35
r: {
36
y: 5,
37
},
38
},
39
},
40
};
41
42
const newData = dfs(data);
43
44
data.c.g.e = 5000;
45
data.c.g.d = 90000;
46
47
console.log("Original data", data);
48
console.log("Copied data", newData);
49
I create a function which will be copy my object without links on old objects. I have a problem, my function doesn’t count the result correctly. Where do i make a mistake?
Advertisement
Answer
dfs without recursion use additional stack to track parent properties.
JavaScript
1
52
52
1
function dfs(data) {
2
let stack = [];
3
let stackres = [];
4
let res = {};
5
6
for (let key in data) {
7
stack.push({ data: data[key], keyData: key });
8
stackres.push(res);
9
10
11
while (stack.length !== 0) {
12
const first = stack.shift();
13
const cur = stackres.shift();
14
15
if (typeof first.data === "object") {
16
cur[first.keyData] = {};
17
for (let key in first.data) {
18
if (typeof first.data[key] === "object") {
19
stack.push({ data: first.data[key], keyData: key });
20
stackres.push(cur[first.keyData]);
21
} else {
22
cur[first.keyData][key] = first.data[key];
23
}
24
}
25
} else {
26
cur[first.keyData] = first.data;
27
}
28
}
29
}
30
31
return res;
32
}
33
const data = {
34
a: 1,
35
b: 2,
36
c: {
37
d: 3,
38
g: {
39
e: 4,
40
r: {
41
y: 5,
42
},
43
},
44
},
45
};
46
const newData = dfs(data);
47
48
data.c.g.e = 5000;
49
data.c.g.d = 90000;
50
51
console.log("Original data", data);
52
console.log("Copied data", newData);