Created
October 1, 2022 09:33
-
-
Save meysampg/3a2cb168fb4e6d0031ac4db12392f3ad to your computer and use it in GitHub Desktop.
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
import scala.language.postfixOps | |
class VectorClock(private var name: String, private var countMap: Map[String, Int] = Map()) { | |
if (!countMap.isDefinedAt(name)) countMap = countMap ++ Map(name -> 1) | |
// increment | |
def ++ = VectorClock( | |
name, | |
countMap ++ Map(name -> (countMap.getOrElse(name, 0) + 1)) | |
) | |
// merge | |
def +(other: VectorClock) = VectorClock( | |
name, | |
(countMap.keySet ++ other.countMap.keySet).map(key => | |
(key, math.max(countMap.getOrElse(key, 0), other.countMap.getOrElse(key, 0))) | |
).toMap ++ Map(name -> (math.max(countMap.getOrElse(name, 0), other.countMap.getOrElse(name, 0)) + 1)) | |
) | |
override def toString: String = s"VectorClock($name, $countMap)" | |
} | |
object VectorClock { | |
def apply(name: String, countMap: Map[String, Int] = Map()): VectorClock = new VectorClock(name, countMap) | |
} | |
val a = VectorClock("A", Map("B" -> 2)) | |
val b = VectorClock("B") | |
println(a) | |
println(b) | |
println(a++) | |
println(a + b) | |
println((a + b)++) |
Author
meysampg
commented
Oct 1, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment