Untitled
unknown
javascript
a year ago
1.9 kB
10
Indexable
class KVStore {
constructor() {
this.lookupMap = {}
this.transaction = []
}
get(key) {
const len = this.transaction.length
if(len){
// search through all transaction
const valueInTransaction = this.transaction.findLast((tran) => {
return tran[key] ?? {}
})
if(valueInTransaction && !valueInTransaction[key]) {
return `can't find key: ${key} in current transaction`
}
return valueInTransaction ? valueInTransaction[key] : this.lookupMap[key] ? this.lookupMap[key] : `can't find key: ${key} in current transaction`
}else {
return this.lookupMap[key] ? this.lookupMap[key] : `can't find key: ${key}`
}
}
set(key, value) {
const len = this.transaction.length
if(len){
this.transaction[len-1][key] = value
}else {
this.lookupMap[key] = value
}
}
delete(key) {
const len = this.transaction.length
if(len) {
this.transaction[len-1][key] = undefined
} else {
delete this.lookupMap[key]
}
}
begin() {
this.transaction.push({})
}
commit() {
if(!this.transaction.length) return "nothing to commit"
const newestTransaction = this.transaction.pop()
const len = this.transaction.length
if(len === 0) {
this.lookupMap = {
...this.lookupMap,
...newestTransaction
}
} else {
this.transaction[len-1] = {
...this.transaction[len-1],
...newestTransaction
}
}
}
rollback() {
if(this.transaction.length) {
this.transaction.pop()
}
}
}Editor is loading...
Leave a Comment