Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ClojureScript のある生活

ayato
December 16, 2015

ClojureScript のある生活

ayato

December 16, 2015
Tweet

More Decks by ayato

Other Decks in Programming

Transcript

  1. ;; dates (.getTime #?(:clj (java.util.Date.) :cljs (js/Date.))) ;; uris #?(

    :clj (defn url-encode [string] (some-> string str (URLEncoder/encode "UTF-8") (.replace "+" "%20"))) :cljs (defn url-encode [string] (some-> string str (js/encodeURIComponent) (.replace "+" "%20")))) ;; reflection warnings #?(:clj (set! *warn-on-reflection* true)) 3FBEFS$POEJUJPOBMT
  2. (ns transit-demo.core (:require [cognitect.transit :as transit]) (:import [java.io ByteArrayInputStream ByteArrayOutputStream]))

    (def custom-writer (transit/write-handler-map {Cart (transit/write-handler (constantly "cart") #(:items %)) Item (transit/write-handler (constantly "item") #(apply vector (vals %)))})) (def out (ByteArrayOutputStream. 4096)) (def writer (transit/writer out :json {:handlers custom-writer})) 5SBOTJU
  3. (defprotocol Calculatable (calculate [x])) (defrecord Cart [items] Calculatable (calculate [self]

    (apply + (map calculate items)))) (defn new-cart [items] (map->Cart {:items items})) (defrecord Item [name price] Calculatable (calculate [self] (* price 1.08))) (defn new-item [name price] (map->Item {:name name, :price price})) 5SBOTJU
  4. (def my-cart-data (new-cart [(new-item "Clojure Programming" 1000) (new-item "Clojure Applied"

    2500)])) (transit/write writer my-cart-data) (.toString out) ;; => "[\"~#cart\",[[\"~#item\",[\"Clojure Programming\",1000]], ;; [\"^1\",[\"Clojure Applied\",2500]]]]" 5SBOTJU
  5. (def custom-reader (transit/read-handler-map {"cart" (transit/read-handler new-cart) "item" (transit/read-handler #(apply new-item

    %))})) (def in (ByteArrayInputStream. (.toByteArray out))) (def reader (transit/reader in :json {:handlers custom-reader})) (def my-cart-data' (transit/read reader)) (calculate my-cart-data') ;; => 3780.0 5SBOTJU