Skip to content

Instantly share code, notes, and snippets.

@fairjm
Last active August 29, 2015 14:05
Show Gist options
  • Save fairjm/e7f90e40df98702dc445 to your computer and use it in GitHub Desktop.
Save fairjm/e7f90e40df98702dc445 to your computer and use it in GitHub Desktop.
a simple event sourcing example to help myself comprehend the idea.
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.HashMap
case class Account(val user:String,val money:Double)
sealed abstract class Op
case class Despoit(val money:Double) extends Op
case class Withdrawal(val money:Double) extends Op
object Bank {
self =>
var editLog = List.empty[Op]
val account = Account("cc",100)
val map = new HashMap[String,List[Account]]
private val KEY = "history"
def push(op:Op):Unit = {
editLog = (op :: editLog.reverse).reverse
map.remove(KEY)
}
def pop():Unit = {
if(!editLog.isEmpty) {
editLog = editLog.tail
map.remove(KEY)
}
}
def now:Account = {
history.last
}
def history: List[Account] = {
val list = map.getOrElse(KEY, {
var list = List.empty[Account]
var account = self.account
for (op <- editLog) {
list = (account :: list.reverse).reverse
op match {
case Despoit(money) => account = Account(account.user, account.money + money)
case Withdrawal(money) => account = Account(account.user, account.money - money)
}
}
list = (account :: list.reverse).reverse
map.put(KEY, list)
list
})
list
}
}
object Main {
def main(args: Array[String]) = {
println(Bank.history)
Bank.push(Despoit(100))
println(Bank.now)
Bank.push(Withdrawal(50))
println(Bank.now)
println(Bank.history)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment