Created
May 30, 2023 22:55
-
-
Save ChukwuEmekaAjah/2fcad08d57931b774d816770a9319f81 to your computer and use it in GitHub Desktop.
This is an implementation of timestamp key-value store that allows historical record of values inserted for a key in a db. This implementation uses a sorted set of timestamps to make sure that the db meets its constraints.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TimeStampDB{ | |
constructor (){ | |
this.db = {} | |
} | |
set(key, timestamp, value){ | |
this.db[key] = this.db[key] || {} | |
this.db[key][timestamp] = value | |
this.db[key]['timestamps'] = this.db[key]['timestamps'] || [] | |
// find insert position for sorted set of timestamps array | |
const position = this.binary_search(timestamp, this.db[key]['timestamps'], 0, this.db[key]['timestamps'].length ) | |
// convert timestamps to set so as de-duplicate timestamps | |
this.db[key]['timestamps'] = Array.from(new Set(this.db[key]['timestamps'].slice(0, position).concat([timestamp]).concat(this.db[key]['timestamps'].slice(position)))) | |
} | |
get(key, timestamp = null){ | |
if(!this.db[key]){ | |
throw new Error('Key does not exist') | |
} | |
if(!timestamp){ | |
// return the last timestamp item inserted into db when timestamp isn't provided | |
return this.db[key][this.db[key]['timestamps'][ this.db[key]['timestamps'].length -1]] | |
} | |
if(this.db[key][timestamp]){ | |
return this.db[key][timestamp] | |
} | |
const next_greater = this.binary_search(timestamp, this.db[key].timestamps, 0, this.db[key].timestamps.length) | |
return this.db[key][this.db[key]['timestamps'][next_greater - 1]] | |
} | |
binary_search(item, array, start = 0, end = 4){ | |
let mid = Math.floor((end + start) / 2) | |
if(start >= end){ | |
return start | |
} | |
if(array[mid] == item) { | |
return mid | |
} | |
if(item < array[mid]){ | |
return this.binary_search(item, array, start, mid) | |
} | |
else if(item > array[mid]){ | |
return this.binary_search(item, array, mid+1, end) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment