@@ -9,6 +9,24 @@ var convertPitch = function(pitch) {
99 }
1010} ;
1111
12+ // my compile/edit in place cause issue when repeat is added
13+ // e.g. output: { tag: 'note', pitch: undefined, dur: 220, start: 940 },
14+ // thus need following shallow copy function, using jQuery style
15+ var copyObject = function ( ) {
16+ var args = Array . prototype . slice . apply ( arguments ) ;
17+ //console.log(args);
18+ var target = args . shift ( 0 ) || { } ;
19+ for ( var i = 0 ; i < args . length ; ++ i ) {
20+ for ( var key in args [ i ] ) {
21+ if ( args [ i ] . hasOwnProperty ( key ) ) {
22+ target [ key ] = args [ i ] [ key ] ;
23+ }
24+ }
25+ }
26+
27+ return target ;
28+ } ;
29+
1230// following compile function is from last lesson
1331var compile = function ( expr ) {
1432
@@ -18,17 +36,29 @@ var compile = function (expr) {
1836 // your code here
1937 ( function ( expr ) {
2038 if ( expr . tag === 'note' || expr . tag === 'rest' ) {
39+ /*
2140 expr.start = time || ref;
2241 if (expr.pitch) {
2342 expr.pitch = convertPitch(expr.pitch);
2443 }
2544 result.push(expr);
45+ */
46+ var note = copyObject ( { } , expr , { start : time || ref } ) ;
47+ if ( expr . pitch ) {
48+ note = copyObject ( note , { pitch : convertPitch ( expr . pitch ) } ) ;
49+ }
50+
51+ result . push ( note ) ;
2652
2753 time += expr . dur ;
2854 } else if ( expr . tag === 'par' ) {
2955 var endLeft = endTime ( 0 , expr . left , time ) ;
3056 var endRight = endTime ( 0 , expr . right , time ) ;
3157 time += endLeft > endRight ? endLeft : endRight ;
58+ } else if ( expr . tag === 'repeat' ) {
59+ for ( var i = 0 ; i < expr . count ; ++ i ) {
60+ arguments . callee ( expr . section ) ;
61+ }
3262 } else {
3363 arguments . callee ( expr . left ) ;
3464 arguments . callee ( expr . right ) ;
@@ -54,10 +84,19 @@ var melody_mus =
5484 } ,
5585 right :
5686 { tag : 'seq' ,
57- left : { tag : 'note' , pitch : 'c4' , dur : 500 } ,
87+ left : { tag : 'repeat' ,
88+ section : { tag : 'note' , pitch : 'c4' , dur : 220 } ,
89+ count : 3
90+ } ,
5891 right : { tag : 'note' , pitch : 'd4' , dur : 500 }
5992 }
6093 } ;
6194
6295console . log ( melody_mus ) ;
6396console . log ( compile ( melody_mus ) ) ;
97+
98+ // testing the copyObject function
99+ //console.log(copyObject());
100+ //console.log(copyObject({}));
101+ //console.log(copyObject({}, {a: 1}));
102+ //console.log(copyObject({}, {a: 1, b: 2}, {b: 3}));
0 commit comments