File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
06_breadth-first_search/es6 Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
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' ) ;
You can’t perform that action at this time.
0 commit comments