Skip to content

Instantly share code, notes, and snippets.

@ianaya89
Created June 13, 2023 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianaya89/f8463c1daf2e401b686156db1b2b3c36 to your computer and use it in GitHub Desktop.
Save ianaya89/f8463c1daf2e401b686156db1b2b3c36 to your computer and use it in GitHub Desktop.
// A core concept in blockchains is the ability to store, update and access the balances of an account. In addition, it allows querying the historical balances of an account as well.
//
// Design a stateful structure allows setting the current balance of an account, as well as retrieving the balance at the current or any previous point in time.
//
// **Interface:**
//
// - `set(account, balance)`
// - `get(account, height)`
// - `increment_height()`
//
// **Example flow:**
//
// - `initialize` // height=0; balances = 0
// - `set(A, 1)`
// - `increment_height()`
// - `set(B, 2)`
// - `increment_height()`
// - `set(A, 3)`
// - `increment_height()`
// - `get(A, 0)` → returns 1
// - `get(B, 0)` → returns 0
// - `get(B, 1)` → returns 2
// - `get(A, 1)` → returns 1
// - `get(B, 2)` -> returns 2
// - `get(A, 2)` → returns 3
class AccountStore {
constructor () {
this.balances = {}
this.height = 0
}
set(account, balance) {
if (!this.balances[account]) {
this.balances[account] = {}
}
this.balances[account][this.height] = balance
}
get(account, height) {
if (!this.balances[account]) {
return 0
}
if (this.balances[account][height]) {
return this.balances[account][height]
}
for (let h = height; h >= 0; h -= 1) {
if (this.balances[account][h]) {
return this.balances[account][h]
}
}
return 0
}
delete (account) {
delete !this.balances[account]
}
incrementHeight () {
this.height += 1
}
}
// TEST
const store = new AccountStore()
store.set('A', 1)
store.incrementHeight()
store.set('B', 2)
store.incrementHeight()
store.set('A', 3)
store.incrementHeight()
store.delete('A')
console.log(store.get('A', 0))
console.log(store.get('B', 0))
console.log(store.get('B', 1))
console.log(store.get('A', 1))
console.log(store.get('B', 2))
console.log(store.get('A', 2))
// console.log(JSON.stringify(store, null, 2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment