Fork me on GitHub
#beginners
<
2017-04-02
>
rgdelato03:04:30

Question: How do you convert a string to a number in ClojureScript? I found myself dropping into the host e.g. js/Number or js/parseInt ...but what's the Clojure way of doing this?

didibus06:04:12

@U47KWM4UV I'd say that's the right way. I don't know ClojureScript, but I do Clojure proper, and it too, relies on using interop to parse strings into host datatype. You'll come to realize that in Clojure and dialects, it is idomatic to embrace the host platform, and not re-invent the wheel when it does a perfectly fine job at the task. A wrapper around js/Number would add nothing, except changing the name of the function. That said, there's a neat trick, for parsing things into Clojure datatype, use clojure.edn/read-string. This will parse string as the Clojure reader would. I think it is cljs.reader/read-string in ClojureScript. read-string parses text as EDN and returns Clojure/Script datatypes. So you can do:

(require '[clojure.edn :as edn])
(type (edn/read-string "23489"))

mikeb04:04:10

Not a cljs expert, but I would say you're doing it fine. Even the clojurescript source uses that method https://github.com/clojure/clojurescript/blob/d0be39660f3a65422c3de6a774ceec0b6a863ee2/src/main/cljs/cljs/stacktrace.cljc#L33

sb19:04:36

Ok, I found out. If you work with reagent and hiccup, then the definition like [:div#id] not works, just like this [:div {:id “id”}] at hiccup side. Therefore I lost one day… maybe that is useful for other beginners too.