11/* Module 6: DGenerics in TypeScript
22 Lab Start */
33
4- /* DataStore is a utility function that can store up to 10 string values in an array.
4+ /* DataStore is a utility function that can store up to 10 string values in an array.
55 Rewrite the DataStore class so the array can store items of any type.
66
77 TODO: Add and apply a type variable. */
8- class DataStore {
9-
10- private _data = new Array ( 10 ) ;
11-
12- AddOrUpdate ( index : number , item : string ) {
13- if ( index >= 0 && index < 10 ) {
14- this . _data [ index ] = item ;
15- } else {
16- alert ( 'Index is greater than 10' )
17- }
8+ class DataStore < T > {
9+ private _data : Array < T > = new Array ( 10 ) ;
10+
11+ AddOrUpdate ( index : number , item : T ) {
12+ if ( index >= 0 && index < 10 ) {
13+ this . _data [ index ] = item ;
14+ } else {
15+ console . log ( "Index is greater than 10" ) ;
1816 }
19- GetData ( index : number ) {
20- if ( index >= 0 && index < 10 ) {
21- return this . _data [ index ] ;
22- } else {
23- return
24- }
17+ }
18+ GetData ( index : number ) {
19+ if ( index >= 0 && index < 10 ) {
20+ return this . _data [ index ] ;
21+ } else {
22+ return ;
2523 }
24+ }
2625}
2726
2827let cities = new DataStore ( ) ;
2928
3029cities . AddOrUpdate ( 0 , "Mumbai" ) ;
3130cities . AddOrUpdate ( 1 , "Chicago" ) ;
32- cities . AddOrUpdate ( 11 , "London" ) ; // item not added
31+ cities . AddOrUpdate ( 11 , "London" ) ; // item not added
3332
34- console . log ( cities . GetData ( 1 ) ) ; // returns 'Chicago'
35- console . log ( cities . GetData ( 12 ) ) ; // returns 'undefined'
33+ console . log ( cities . GetData ( 1 ) ) ; // returns 'Chicago'
34+ console . log ( cities . GetData ( 12 ) ) ; // returns 'undefined'
3635
3736// TODO Test items as numbers.
38-
39-
37+ let empIDs = new DataStore < number > ( ) ;
38+ empIDs . AddOrUpdate ( 0 , 50 ) ;
39+ empIDs . AddOrUpdate ( 1 , 65 ) ;
40+ empIDs . AddOrUpdate ( 2 , 89 ) ;
41+ console . log ( empIDs . GetData ( 0 ) ) ; // returns 50
4042// TODO Test items as objects.
43+ type Pets = {
44+ name : string ;
45+ breed : string ;
46+ age : number
47+ }
48+ let pets = new DataStore < Pets > ( ) ;
49+ pets . AddOrUpdate ( 0 , { name : 'Rex' , breed : 'Golden Retriever' , age : 5 } ) ;
50+ pets . AddOrUpdate ( 1 , { name : 'Sparky' , breed : 'Jack Russell Terrier' , age : 3 } ) ;
51+ console . log ( pets . GetData ( 1 ) ) ; // returns { name: 'Sparky', breed: 'Jack Russell Terrier', age: 3 }
0 commit comments