Skip to content

Instantly share code, notes, and snippets.

@jcipriano
Created July 7, 2017 19:28
Show Gist options
  • Save jcipriano/f99cde111f2276e747d0228db8e4aeec to your computer and use it in GitHub Desktop.
Save jcipriano/f99cde111f2276e747d0228db8e4aeec to your computer and use it in GitHub Desktop.
/*
Implement a key-value store that presents the following minimal interface:
`put(k, v)`
`get(k, timestamp=None)`
When a timestamp is specified for the `get` operation, the `get` should return
the value that was associated with the key at that point in time. (Semantically,
this should be equivalent to getting in a time machine, going back to that point
in time, and then asking the key-value store for the current value.)
*/
var key_values = []
function put (key, value) {
if (!key_values[key]) {
key_values[key] = []
}
var value_to_insert = {
value: value,
time: new Date()
}
if (key_values[key]) {
key_values[key].push(value_to_insert)
}
return value_to_insert;
}
function get (key, timestamp) {
// return latest value if not timestamp provided
if (!timestamp) {
return key_values[key][key_values.length]
}
console.log('looking up value for time:', timestamp)
var values = key_values[key]
// if timestamp is greater than that of last value inserted, return it
var last_item_added = values[values.length-1]
if (timestamp >= last_item_added.time) {
return last_item_added.value
}
for (var i=0; i<values.length; i++) {
var time = values[i].time
var next_time = values[i+1].time
if (timestamp >= time) {
if (timestamp < next_time) {
return values[i].value
}
}
}
}
// save time for testing
var past_time = put('foo','value').time
// to ensure we have a different timestamp
setTimeout(function () {
put('foo','value2')
// should return first value inserted
console.log( get('foo', past_time) )
// should return last value inserted
// console.log( get('foo', new Date()) )
}, 500)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment