Skip to content

Instantly share code, notes, and snippets.

@smee
Created July 20, 2018 14:21
Show Gist options
  • Select an option

  • Save smee/8962d2d09713114436375ca4795d4af0 to your computer and use it in GitHub Desktop.

Select an option

Save smee/8962d2d09713114436375ca4795d4af0 to your computer and use it in GitHub Desktop.
(defn js->clj
"Recursively transforms JavaScript arrays into ClojureScript
vectors, and JavaScript objects into ClojureScript maps. With
option ':keywordize-keys true' will convert object fields from
strings to keywords."
([x] (js->clj x :keywordize-keys false))
([x & opts]
(let [{:keys [keywordize-keys]} opts
keyfn (if keywordize-keys keyword str)
f (fn thisfn [x]
(cond
(satisfies? IEncodeClojure x)
(-js->clj x (apply array-map opts))
(seq? x)
(doall (map thisfn x))
(map-entry? x)
(MapEntry. (thisfn (key x)) (thisfn (val x)) nil)
(coll? x)
(into (empty x) (map thisfn) x)
(array? x)
(persistent!
(reduce #(conj! %1 (thisfn %2))
(transient []) x))
(identical? (type x) js/Object)
(persistent!
(reduce (fn [r k] (assoc! r (keyfn k) (thisfn (gobject/get x k))))
(transient {}) (js-keys x)))
:else x))]
(f x))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment