Search code examples
clojureclojurescriptreagent

Why clojure function is not working or crashing in core.cljs [reagent]?


I have a function encode that takes a seed and message to return a cipher.

My issue is that when I tried to use it in my core.cljs file with reagent, the function is silently failing (returning an empty string).

I feel like I'm doing something (or approach) wrong so any quick pointers will be highly appreciated.

(prn (encode "testing" "test"))           ;;> ""
(prn (type encode))                       ;;> #object[Function]
(prn (type (encode "testing" "jordan")))  ;;> #object[String]

For example I was expecting: "mikmbry" from (encode "testing" "test"). Everything works on the repl but silently fails on core.cljs.

Thanks for your time.


Solution

  • Your code has an issue with handling Strings in ClojureScript.

    JavaScript doesn't have character type and ClojureScript doesn't introduce its own type. Instead when you treat a string as a sequence, it's individual elements will be one-character long strings:

    (seq "ABC")
    ;; => ("A" "B" "C")
    

    If you need to get the ASCII number value of a character you need to use JavaScript's String.charCodeAt(index):

    (.charCodeAt "A" 0)
    ;; => 65
    

    To convert a number (as ASCII code) into a string you can use String.fromCharCode:

    (js/String.fromCharCode 65)
    ;; => "A"