-
-
Notifications
You must be signed in to change notification settings - Fork 273
/
Copy pathsearch.util.js
40 lines (38 loc) · 1.15 KB
/
search.util.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
/* eslint-disable no-plusplus */
/* eslint-disable max-len */
/* eslint-disable consistent-return */
// eslint-disable-next-line max-len
/* we have to do a search because undo/redo saves payloads as deep clones so passing a memory ref would be detrimental
This will find you the actual object by ID
*/
const breadthFirstSearch = (array, id) => {
const queue = [...array.filter(el => typeof el === 'object')]
while (queue.length) {
const evaluated = queue.shift()
if (evaluated.id === id) {
return evaluated
}
if (evaluated.children.length) {
queue.push(...evaluated.children)
}
}
}
// this would find you the parent of a given id
const breadthFirstSearchParent = (array, id) => {
const queue = [...array.filter(el => typeof el === 'object')]
while (queue.length) {
const evaluated = queue.shift()
for (let i = 0; i < evaluated.children.length; i++) {
if (evaluated.children[i].id === id) {
return {
evaluated,
index: i
}
}
if (evaluated.children.length) {
queue.push(...evaluated.children)
}
}
}
}
export { breadthFirstSearch, breadthFirstSearchParent }