Skip to content

Instantly share code, notes, and snippets.

@volgar1x
Last active December 14, 2015 10:59
Show Gist options
  • Save volgar1x/5076135 to your computer and use it in GitHub Desktop.
Save volgar1x/5076135 to your computer and use it in GitHub Desktop.
package org.mojito.core
import collection.mutable
/**
* @author Blackrush
* @todo implement Iterable[(Seq[K], V)]
*/
class NavigableTree[K, V](val key: K, val value: Option[V] = None, val parent: Option[NavigableTree[K, V]] = None) {
type This = NavigableTree[K, V]
private val children = new mutable.HashMap[K, This]
def hasChildren = !children.isEmpty
def root: This = if (parent.isEmpty) this else parent.get.root
def path: Seq[K] = parent match {
case None => Seq.empty
case Some(p) => p.path :+ key
}
def get(key: K): Option[V] = children.get(key) match {
case Some(v) => v.value
case None => None
}
def put(key: K, value: Option[V]): This = {
val child = new This(key, value, Some(this))
children(key) = child
child
}
private def recGet(it: Iterator[K]): Option[V] =
if (!it.hasNext) value
else children.get(it.next()) match {
case Some(child) => child.recGet(it)
case None => value
}
private def recPut(it: Iterator[K], value: Option[V]): This = {
val key = it.next()
if (!it.hasNext) put(key, value)
else children.get(key).getOrElse(put(key, None)).recPut(it, value)
}
def get(keys: Seq[K]): Option[V] = recGet(keys.iterator)
def put(keys: Seq[K], value: Option[V]): This = {
val it = keys.iterator
if (it.hasNext) recPut(it, value)
else throw new UnsupportedOperationException
}
def apply(key: K): Option[V] = get(key)
def apply(keys: Seq[K]): Option[V] = get(keys)
def put(key: K, value: V): This = put(key, Option(value))
def put(keys: Seq[K], value: V): This = put(keys, Option(value))
def update(key: K, value: Option[V]) = put(key, value)
def update(key: K, value: V) = put(key, value)
def update(keys: Seq[K], value: Option[V]) = put(keys, value)
def update(keys: Seq[K], value: V) = put(keys, value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment