Wait for the save, not the clock

A save can finish before or after a fixed pause.

your task

Print the stored status when each save finishes. All three cases must print “stored: confirmed”. Complete the task without choosing a longer pause.

The starter reads stored after 50 milliseconds. The 30 ms save has finished. The 80 ms and 400 ms saves still report “held”. The exercise controls the clock. saveBooking can notify your code when it finishes.

Starter code
or press Ctrl EnterNot run yet

cases

Not run yetThe save takes 30 ms

Expected output

1stored: confirmed
See the input and the code for this case
let now = 0;
const timers = [];
function wait(ms, callback) {
  timers.push({ at: now + ms, callback });
}
function advance(ms) {
  const end = now + ms;
  for (;;) {
    timers.sort((a, b) => a.at - b.at);
    if (timers.length === 0 || timers[0].at > end) break;
    const next = timers.shift();
    now = next.at;
    next.callback();
  }
  now = end;
}

let stored = "held";
function saveBooking(status, onSaved) {
  wait(30, () => {
    stored = status;
    if (onSaved) onSaved();
  });
}
advance(200);
Not run yetThe save takes 80 ms

Expected output

1stored: confirmed
See the input and the code for this case
let now = 0;
const timers = [];
function wait(ms, callback) {
  timers.push({ at: now + ms, callback });
}
function advance(ms) {
  const end = now + ms;
  for (;;) {
    timers.sort((a, b) => a.at - b.at);
    if (timers.length === 0 || timers[0].at > end) break;
    const next = timers.shift();
    now = next.at;
    next.callback();
  }
  now = end;
}

let stored = "held";
function saveBooking(status, onSaved) {
  wait(80, () => {
    stored = status;
    if (onSaved) onSaved();
  });
}
advance(200);
Not run yetThe save takes 400 ms

Expected output

1stored: confirmed
See the input and the code for this case
let now = 0;
const timers = [];
function wait(ms, callback) {
  timers.push({ at: now + ms, callback });
}
function advance(ms) {
  const end = now + ms;
  for (;;) {
    timers.sort((a, b) => a.at - b.at);
    if (timers.length === 0 || timers[0].at > end) break;
    const next = timers.shift();
    now = next.at;
    next.callback();
  }
  now = end;
}

let stored = "held";
function saveBooking(status, onSaved) {
  wait(400, () => {
    stored = status;
    if (onSaved) onSaved();
  });
}
advance(1000);