Skip to content

Commit 88cf645

Browse files
drytikovegonSchiele
authored andcommitted
add es6 code for breadth-first-search
1 parent eec9c31 commit 88cf645

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
const graph = {};
2+
graph.you = ['alice', 'bob', 'claire'];
3+
graph.bob = ['anuj', 'peggy'];
4+
graph.alice = ['peggy'];
5+
graph.claire = ['thom', 'jonny'];
6+
graph.anuj = [];
7+
graph.peggy = [];
8+
graph.thom = [];
9+
10+
const isSeller = name => name[name.length - 1] === 'm';
11+
12+
const search = (name, graph) => {
13+
const iter = (waited, visited) => {
14+
if (waited.length === 0) {
15+
return false;
16+
}
17+
const [current, ...rest] = waited;
18+
if (visited.has(current)) {
19+
return iter(rest, visited);
20+
}
21+
if (isSeller(current)) {
22+
console.log(`${current} is a mango seller!`);
23+
return true;
24+
}
25+
visited.add(current);
26+
const personFriends = graph[current];
27+
return iter([...rest, ...personFriends], visited);
28+
};
29+
return iter(graph[name], new Set());
30+
};
31+
32+
search('you');

0 commit comments

Comments
 (0)