Skip to content

Instantly share code, notes, and snippets.

@souenzzo
Last active July 10, 2017 03:19
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 souenzzo/46da88205f90f5ffba0c0a11b8f32119 to your computer and use it in GitHub Desktop.
Save souenzzo/46da88205f90f5ffba0c0a11b8f32119 to your computer and use it in GitHub Desktop.
Proposal for clj->js
(declare clj->js)
(defn key->js
([k] (key->js k clj->js))
([k primitive-fn]
(cond
(satisfies? IEncodeJS k) (-key->js k)
(or (string? k)
(number? k)
(keyword? k)
(symbol? k)) (primitive-fn k)
:default (pr-str k))))
(defn clj->js
"Recursively transforms ClojureScript values to JavaScript.
sets/vectors/lists become Arrays, Keywords and Symbol become Strings,
Maps become Objects. Arbitrary keys are encoded to by key->js."
[x & {:keys [keyword-fn]
:or {keyword-fn name}}]
(letfn [(keyfn [k] (key->js k thisfn))
(thisfn [x] (cond
(nil? x) nil
(satisfies? IEncodeJS x) (-clj->js x)
(keyword? x) (keyword-fn x)
(symbol? x) (str x)
(map? x) (let [m (js-obj)]
(doseq [[k v] x]
(gobject/set m (keyfn k) (thisfn v)))
m)
(coll? x) (let [arr (array)]
(doseq [x (map thisfn x)]
(.push arr x))
arr)
:else x))]
(thisfn x)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment