Save Only the Latest Draft
Write the code, see it run, pass the checks.
The problem
- medium
- Code
- Pro
Write createSaver(save), for autosaving a document. save(value) returns a promise. Return a function request(value) that returns a promise. Never run two saves at once. If no save is running, call save(value) straight away, during the request call. If one is running, keep value as the next one to save, replacing any value already waiting: only the latest value that arrived during a save gets saved after it, and the ones it replaced are skipped. When a save finishes, whether it resolved or rejected, start the waiting one, if there is one. A request's promise settles the same way as the save that covered it: the save of its own value or, if its value was replaced, the save of the value that replaced it.
Your code must pass
- Starts a save at once when none is running
- Never runs two saves at once
- Saves only the latest value that arrived during a save
- Settles each request with the save that covered it
- Keeps going after a failed save