Sunday, May 8, 2016

How to convert google visualization PieChart to ClojureScript PieChart

Conversion from JScript to ClojureScript in beginning could be difficult if do not follow basic rules:
1. Try do not remove  JScript libraries  and rely on  ClojureScript loading them.
 For  example:
(.load js/google "visualization" "1.0" {"packages" ["corechart"]})
  removes JScript library load :  
 google.charts.load("current", {packages:["corechart"]});

Remove it only  at last moment when you 100% sure so your code functional
2.Use  ClojureScript construction doto :
      <JScript object>.<JScript funcion name>(<function value> )  Converted to   
     (doto  < JScript object>  (.<JScript function name> <function value>))
Example:
  (doto data-table 
        (.addColumn #js { :type "string", :id "Topping"})
        (.addColumn #js { :type "number", :id "slices"})
        (.addRows (some-data-function)))

Let's convert PieChart of google visualization package:

    

Use Clojure hashmap constructions. In ClojureScript there is function which does conversion to JSON :
;Function definition
(defn clj->json
  [ds]
  (.stringify js/JSON (clj->js ds)))
;Usage
(let [json (clj->json data-structure)]
  ;; do something with json
  )
But Google.visualization is in JScript not in Clojure .Not a big deal let's convert this JScript to ClojureScript:
(enable-console-print!)
(println "Hello world!")
 ;; data to be used for the viz
(def my-data [
 ;; the format here is 
["Mushrooms" 3] ["Onions" 1] ["Olives" 1]])


(defn draw-chart []
(let [container (.getElementById js/document "chart_div")
     chart (js/google.visualization.PieChart. container)
  options (chart-options)
  data-table (js/google.visualization.DataTable. chart)]
  (doto data-table 
        (.addColumn #js { :type "string", :id "Topping"})
  (.addColumn #js { :type "number", :id "slices"})
  (.addRows (clj->js my-data)))
     (.draw chart data-table options)))

(defn chart-options []
(clj->js {:title "How much Pizza i ate last night" :width 400 :height 300 :is3D true}))


(.load js/google "visualization" "1.0" {"packages" ["corechart"]})

(.setOnLoadCallback js/google draw-chart)
This is example of my HTML code which call this ClojureScript:


  clojure-script
  


    
If you come till this point and didn't get in . Read this blog which I used to create this example: https://micahasmith.github.io/2015/10/19/clojurescript-is-easy/

No comments: