Skip to content

Commit f83f319

Browse files
committed
add the author's implementation for future reference
1 parent c715107 commit f83f319

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

nathansununiversity_02_author.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
var endTime = function (time, expr) {
2+
if (expr.tag === 'note') return time + expr.dur;
3+
if (expr.tag === 'seq')
4+
return endTime(endTime(time, expr.left), expr.right);
5+
return Math.max(endTime(time, expr.left), endTime(time, expr.right));
6+
};
7+
8+
var compileT = function (musexpr, time) {
9+
if (musexpr.tag === 'note') {
10+
return [ { tag: 'note',
11+
pitch: musexpr.pitch,
12+
start: time,
13+
dur: musexpr.dur } ];
14+
}
15+
if (musexpr.tag === 'seq') {
16+
var left = compileT(musexpr.left, time);
17+
var ldur = endTime(time, musexpr.left);
18+
var right = compileT(musexpr.right, ldur);
19+
return left.concat(right);
20+
}
21+
if (musexpr.tag === 'par') {
22+
var left = compileT(musexpr.left, time);
23+
var right = compileT(musexpr.right, time);
24+
return left.concat(right);
25+
}
26+
};
27+
28+
var compile = function (musexpr) {
29+
return compileT(musexpr, 0);
30+
};
31+
32+
var melody_mus =
33+
{ tag: 'seq',
34+
left:
35+
{ tag: 'par',
36+
left: { tag: 'note', pitch: 'c3', dur: 250 },
37+
right: { tag: 'note', pitch: 'g4', dur: 500 } },
38+
right:
39+
{ tag: 'par',
40+
left: { tag: 'note', pitch: 'd3', dur: 500 },
41+
right: { tag: 'note', pitch: 'f4', dur: 250 } } };
42+
43+
console.log(melody_mus);
44+
console.log(compile(melody_mus));

0 commit comments

Comments
 (0)