File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed
06_breadth-first_search/javascript Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ 'use strict' ;
2
+
3
+ function person_is_seller ( name ) {
4
+ return name [ name . length - 1 ] === 'm' ;
5
+ }
6
+
7
+ const graph = { } ;
8
+ graph [ "you" ] = [ "alice" , "bob" , "claire" ] ;
9
+ graph [ "bob" ] = [ "anuj" , "peggy" ] ;
10
+ graph [ "alice" ] = [ "peggy" ] ;
11
+ graph [ "claire" ] = [ "thom" , "jonny" ] ;
12
+ graph [ "anuj" ] = [ ] ;
13
+ graph [ "peggy" ] = [ ] ;
14
+ graph [ "thom" ] = [ ] ;
15
+ graph [ "jonny" ] = [ ] ;
16
+
17
+
18
+ function search ( name ) {
19
+ let search_queue = [ ] ;
20
+ search_queue = search_queue . concat ( graph [ name ] ) ;
21
+ // This array is how you keep track of which people you've searched before.
22
+ const searched = [ ] ;
23
+ while ( search_queue . length ) {
24
+ let person = search_queue . shift ( ) ;
25
+ // Only search this person if you haven't already searched them
26
+ if ( searched . indexOf ( person ) === - 1 ) {
27
+ if ( person_is_seller ( person ) ) {
28
+ console . log ( person + ' is a mango seller!' ) ;
29
+ return true ;
30
+ } else {
31
+ search_queue = search_queue . concat ( graph [ person ] ) ;
32
+ // Marks this person as searched
33
+ searched . push ( person ) ;
34
+ }
35
+ }
36
+ }
37
+ return false ;
38
+ }
39
+
40
+
41
+ search ( 'you' ) ; // thom is a mango seller!
You can’t perform that action at this time.
0 commit comments