Skip to content

Instantly share code, notes, and snippets.

@joinr
Last active March 21, 2024 00:20
Show Gist options
  • Save joinr/50737def18e8ca927ee0ec85bfbcde88 to your computer and use it in GitHub Desktop.
Save joinr/50737def18e8ca927ee0ec85bfbcde88 to your computer and use it in GitHub Desktop.
messing with transit to avoid the clj->js tax
(require '[cognitect.transit :as t])
(def jt js/transit)
(def r (t/reader :json))
(def w (t/writer :json))
(def jr (jt.reader "json"))
(def the-obj (clj->js {"a" [1 2 3] "b" [4 5 6] "c" {"d" {"e" [7 8 9]}}}))
(def the-json (js/JSON.stringify the-obj))
(defn map->obj [m]
(let [res #js{}]
(.forEach m (fn [v k]
(if (transit.isMap v)
(aset res k (map->obj v))
(aset res k v))))
res))
(defn demo-transit [json-txt]
(let [m (t/read r json-txt)
{a "a" b "b"} m
result (assoc m "z" (+ (a 0) (b 0)))]
(map->obj (.read jr (t/write w result)))))
(defn demo-cljs [json-txt]
(let [m (js->clj (js/JSON.parse json-txt))
{a "a" b "b"} m
result (assoc m "z" (+ (a 0) (b 0)))]
(clj->js result)))
#_
(defmacro jslet [bindings & body]
(let [new-binds (->> (for [[l r] (partition 2 bindings)]
(if (and (map? l) (l :fields))
(let [flds (l :fields)
fbinds (for [f flds]
`[~f (aget ~r ~(name f))])]
(apply concat fbinds))
[l r]))
(apply concat))]
`(let [~@new-binds] ~@body)))
(defn demo-js [json-txt]
(let [m (js/JSON.parse json-txt)
a (aget m "a")
b (aget m "b")]
(aset m "z" (+ (nth a 0) (nth b 0)))
m))
;; cljs.user> (demo-transit the-json)
;; #js{:a #js[1 2 3], :b #js[4 5 6], :c #js{:d #js{:e #js[7 8 9]}}, :z 5}
;; cljs.user> (demo-cljs the-json)
;; #js{:a #js[1 2 3], :b #js[4 5 6], :c #js{:d #js{:e #js[7 8 9]}}, :z 5}
;;cljs.user> (demo-js the-json)
;;#js{:a #js[1 2 3], :b #js[4 5 6], :c #js{:d #js{:e #js[7 8 9]}}, :z 5}
;; cljs.user> (time (dotimes [i 10000] (demo-cljs the-json)))
;; "Elapsed time: 297.000000 msecs"
;; cljs.user> (time (dotimes [i 10000] (demo-transit the-json)))
;; "Elapsed time: 136.000000 msecs"
;;nil
;;cljs.user> (time (dotimes [i 10000] (demo-js the-json)))
;;"Elapsed time: 13.000000 msecs"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment