44
55// Imperative
66
7- const marcus = {
7+ const marcus1 = {
88 name : 'Marcus Aurelius' ,
99 born : 121 ,
10+ upperName ( ) {
11+ this . name = this . name . toUpperCase ( ) ;
12+ } ,
1013 get era ( ) {
1114 return this . born < 0 ? 'BC' : 'AD' ;
1215 } ,
@@ -15,13 +18,41 @@ const marcus = {
1518 } ,
1619} ;
1720
18- console . log ( `${ marcus } ` ) ;
21+ marcus1 . name += ' Antoninus' ;
22+ marcus1 . city = 'Roma' ;
23+ marcus1 . position = 'emperor' ;
24+ marcus1 . upperName ( ) ;
25+ console . log ( `Era of ${ marcus1 . name } birth is ${ marcus1 . era } ` ) ;
26+ console . log ( `${ marcus1 } ` ) ;
27+ const keys = Object . keys ( marcus1 ) ;
28+ console . log ( 'Fields:' , keys . join ( ', ' ) ) ;
1929
2030// Functional
2131
2232const era = year => ( year < 0 ? 'BC' : 'AD' ) ;
2333const person = ( name , born ) => ( ) => `${ name } was born in ${ born } ${ era ( born ) } ` ;
2434
2535const marcus2 = person ( 'Marcus Aurelius' , 121 , 'Roma' ) ;
26-
2736console . log ( marcus2 ( ) ) ;
37+
38+ // Object reflection
39+
40+ const omap = ( obj , fn ) => Object . keys ( obj )
41+ . reduce ( ( res , key ) => {
42+ const [ prop , val ] = fn ( key , obj [ key ] ) ;
43+ res [ prop ] = val ;
44+ return res ;
45+ } , { } ) ;
46+
47+ const marcus3 = {
48+ firstName : 'Marcus' ,
49+ middleName : 'Aurelius' ,
50+ lastName : 'Antoninus' ,
51+ } ;
52+
53+ const marcus4 = omap ( marcus3 , ( key , val ) => {
54+ const prop = key . toLowerCase ( ) . replace ( 'name' , '' ) ;
55+ const value = val . toUpperCase ( ) ;
56+ return [ prop , value ] ;
57+ } ) ;
58+ console . log ( marcus4 ) ;
0 commit comments