Skip to content

Instantly share code, notes, and snippets.

@jprudent
Created January 12, 2016 12:00
Show Gist options
  • Save jprudent/498ce9c18742f2ff836f to your computer and use it in GitHub Desktop.
Save jprudent/498ce9c18742f2ff836f to your computer and use it in GitHub Desktop.
A simple implementation of consitant hashing in Clojure
(defprotocol ConsistentHashRing
(add-node [this node] "add node to the ring")
(remove-node [this node] "remove node and its replicas of the ring")
(find-node [this data] "find the node responsible of data"))
(defn- find-closest-key [xs h]
(or (first (drop-while #(> h %) xs))
(first xs)))
(extend-protocol ConsistentHashRing
PersistentTreeMap
(add-node [this node] (assoc this (.hashCode node) node))
(remove-node [this node] (dissoc this (.hashCode node)))
(find-node [this data] (this (find-closest-key (keys this) (.hashCode data)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment