8krwqg
Last Updated: February 25, 2016
·
2.551K
· rodnaph
6e283a554e50ee3d10e5386f85816463

Clojure/Script Compatibility Magic

I just had a library that I'm trying to maintain Clojure AND ClojureScript compatibility with (using crossovers), and needed to parse an integer from a string. Easy you'd think... But unfortunately the Clojure way...

(Integer/parseInt "123")

And the ClojureScript way...

(js/parseInt "123")

Aren't going to be compilable in a single namespace. With lein-cljsbuild I believe you can supply different namespace implementations for each language, but for such a small tweak I looked for a simpler way. I found it with a little lein-cljsbuild dark magic.

The following string can be included in .clj source files, and is removed when processing to .cljs.

;*CLJSBUILD-REMOVE*;

So with a little hackery...

(ns mynamespace)

;*CLJSBUILD-REMOVE*;(js* "window.Integer = {parseInt: parseInt};")

We have an accessible function in ClojureScript (radix excluded for brevity) which matches the Clojure equivalent! Happy days.

This kind of monkey patching is certainly not the technique you should normally use, but can be useful in certain situations

Say Thanks
Respond

1 Response
Add your response

8712
Me

That's what cljx is for.

over 1 year ago ·