2013. október 18., péntek

ClojureScript string to integer

Str to int.

;; with some java interop
(Integer/parseInt "31") 
;; => 31

(Integer/parseInt "asd")
;; => NumberFormatException
;; okay then. we need to check for number format.

(defn str->int
  [s] 
  (when (re-matches #"^\d+$" s)
    (Integer/parseInt s)))

;; or a solution with no interop:

(defn str->int
  [s]
  (when (and (string? s)
        (re-find #"^\d+$" s))
    (read-string s)))


Problem

When dealing with external data in Clojure/ClojureScript, we often receive numeric values as strings from outer sources. Converting data to the right type is not always straightforward. Looking for a solution, I considered the following aspects.

Clean

Write small and straightforward functions. Use suggestive but short names and doc strings when needed.

Perform

Also, avoid interop when possible. When performance is a major issue, implementing your functions in native java is a winner anyways.

Secure

Be clear about use cases of functions. What do your functions do when arguments of wrong type are supplied? Did you think about nil arguments?

Also, please note: when using read-string, always bound *read-eval* to false to stop malicious data being executed. read-string drops a RuntimeException on malformed or empty string.