function play_tune(melody) {
let played_notes = [];
let durations = [];
let positions = [];
let wait_time = 0;
let time_passed = 0;
console.log("Melody initiation.")
for (let key in melody) {
played_notes.push(melody[key].note);
durations.push(melody[key].lasts);
positions.push(melody[key].starts_at);
}
for (let i in positions) {
if (positions[i] > positions[i - 1]) {
wait_time = positions[i] - wait_time;
console.log("Wait " + wait_time + " second(s).");
console.log("Play " + played_notes[i]);
} else {
console.log("Play " + played_notes[i]);
}
if (positions[i] == positions[i - 1] && durations[i] == durations[i - 1] || positions[i] + durations[i] == durations[i - 1]) {
//do nothing.
} else {
time_passed += durations[i];
}
if ((durations[i] + positions[i]) < time_passed || durations[i] < time_passed) {
console.log(played_notes[i] + " released.")
}
}
return "Melody ends.";
}
let my_melody = [{
note: 'C',
starts_at: 0,
lasts: 4
},
{
note: 'E',
starts_at: 0,
lasts: 4
},
{
note: 'G',
starts_at: 2,
lasts: 2
},
{
note: 'G#',
starts_at: 3,
lasts: 2
},
{
note: 'Eb',
starts_at: 3,
lasts: 2
}
];
console.log(play_tune(my_melody))
This code is designed to display musical notes in the correct sequence, including when they start, the duration between them, and when to release each note. Each object in the array contains the note name, starting position in seconds, and duration (also in seconds).
It works mostly as expected when looping through each element by index. However, releasing the notes in the correct order proves challenging as I cannot reference notes that appear before the current index. The current implementation is static and needs to be dynamic regardless of the note order.
if ((durations[i] + positions[i]) < time_passed || durations[i] < time_passed){
console.log((played_notes[i] + played_notes[i-1] + played_notes[i-2]) + " released.")
}
When running the code, only the note "G" is released. "C" and "E" are not released. Furthermore, "G#" and "Eb" do not release simultaneously; they play and release consecutively.
Also, the "Wait x second(s)." message before "G#" and "Eb" are played is missing.
The expected console output should be:
Melody initiation.
Play C
Play E
Wait 2 second(s).
Play G
Wait 1 second(s).
Play G#
Play Eb
C released.
E released.
G released.
Wait 1 second(s).
G# released.
Eb released.
Melody ends.
Due to limitations, advanced features such as foreach loops are not allowed. The solution should be kept as simple as possible using basic constructs like for loops, while loops, if statements, and array and object functions.