-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsolution.js
67 lines (51 loc) · 1.68 KB
/
solution.js
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const contains = (store, product) =>
store instanceof Object ? Object.values(store).some(item => contains(item, product)) : store === product;
const containsStringify = (store, product) => JSON.stringify(store).includes(JSON.stringify(product));
// Depth-first tree traversal with recursion
const containsDFRecursive = (store, product) => {
if (store === product) {
return true;
}
const storeKeys = store instanceof Object ? Object.keys(store) : [];
for (const key of storeKeys) {
const nestedItem = store[key];
const isMatch = containsDFRecursive(nestedItem, product);
if (isMatch) {
return true;
}
}
return false;
};
// Depth-first tree traversal without recursion
const containsDFNonRecursive = (store, product) => {
const storeStack = [store];
while (storeStack.length > 0) {
const currentItem = storeStack.shift();
if (currentItem === product) {
return true;
}
const storeKeys = currentItem instanceof Object ? Object.keys(currentItem) : [];
for (const key of storeKeys) {
const nestedItem = currentItem[key];
storeStack.unshift(nestedItem);
}
}
return false;
};
// Breadth-first tree traversal
const containsBF = (store, product) => {
const queue = [store];
while (queue.length > 0) {
const currentItem = queue.shift();
if (currentItem === product) {
return true;
}
const storeKeys = currentItem instanceof Object ? Object.keys(currentItem) : [];
for (const key of storeKeys) {
const nestedItem = currentItem[key];
queue.push(nestedItem);
}
}
return false;
};
export { contains, containsStringify, containsDFRecursive, containsDFNonRecursive, containsBF };