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