Last active
February 16, 2016 04:37
-
-
Save devth/5dbf2909f4440fd047fa to your computer and use it in GitHub Desktop.
This file contains 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
(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