Key-value store returning each key's value as of any time
A collaborative settings service replays changes coming from many devices. Each change carries the time it was made on its device, and because of network delays the changes reach the server out of order. The service must answer “what was this setting at time t?” for any key and any time, so audit screens can show the settings as they were at any moment.
Implement a TimestampedStore class.
const store = new TimestampedStore();
store.set(key, value, time); // records value for key at time
store.delete(key, time); // records that key was deleted at time
store.get(key, time); // => the value of key at time, or undefined
key is a string. time is a finite number (it can be negative or fractional). value is any value except undefined, including null, 0, '', and objects (returned by reference).get(key, time) finds the record for key with the largest time that is less than or equal to time. If that record is a value, return it. If it is a deletion, or there is no such record, return undefined.delete does not erase history: queries for times before the deletion still see the old value, and a later set brings the key back.set and delete return nothing.get should binary-search them rather than scan them all.const store = new TimestampedStore();
store.set('theme', 'light', 10);
store.set('theme', 'dark', 30);
store.set('theme', 'sepia', 20); // arrives late
store.delete('theme', 40);
store.get('theme', 5); // => undefined (nothing recorded yet)
store.get('theme', 10); // => 'light'
store.get('theme', 25); // => 'sepia'
store.get('theme', 35); // => 'dark'
store.get('theme', 40); // => undefined (deleted at 40)
store.get('lang', 50); // => undefined (unknown key)
store.set('theme', 'dark', 50);
store.get('theme', 45); // => undefined
store.get('theme', 60); // => 'dark'
store.set('theme', 'contrast', 20); // same time as 'sepia': replaces it
store.get('theme', 25); // => 'contrast'