-
-
Save souenzzo/46da88205f90f5ffba0c0a11b8f32119 to your computer and use it in GitHub Desktop.
Proposal for clj->js
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
(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