Skip to content

Instantly share code, notes, and snippets.

@devth
Last active February 16, 2016 04:37
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 devth/5dbf2909f4440fd047fa to your computer and use it in GitHub Desktop.
Save devth/5dbf2909f4440fd047fa to your computer and use it in GitHub Desktop.
(defn- ensure-min-vec-size [v size]
"Ensure v has at least size elements. Fill with `nil` if necessary."
(let [d (- size (count v))]
(if (> d 0) (into v (vec (repeat d nil))) v)))
(defn- find-or-create
"Build up nested path with possibly-numeric indices as vectors and other keys
as maps"
[m [k1 k2 & path]]
(let [ds (cond-> (get-in m [k1] (if (number? k2) (vec (repeat k2 nil)) {}))
;; if k2 is a number we need to ensure the vector is large enough
(number? k2) (ensure-min-vec-size k2)
;; recurse if path is non nil
path (find-or-create (into [k2] path)))]
(update-in m [k1] (constantly ds))))
(defn- update-in-idx
"Like clojure.core/update-in except creates vectors insated of hash-maps when
key is a number"
[m path v]
(update-in (find-or-create m path) path (constantly v)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment