Create a gist now

Instantly share code, notes, and snippets.

Staltz's recommender translated to clojurescript https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
(ns rxcljs-test.core
(:require [clojure.browser.repl :as repl]
[clojure.string :as string]
[rxcljs-test.viz :as viz]
[rx-cljs.observable :as rx]
))
(enable-console-print!)
(println "Hello world!")
(defn show [obs]
(rx/subscribe obs #(prelog (.stringify js/JSON (clj->js %)))))
(defn ajax [url]
(rx/create (fn [obs]
(let [xhr (js/XMLHttpRequest.)]
(.open xhr "get" url)
(set! (.-responseType xhr) "json")
(.addEventListener
xhr "error"
(fn [error]
(.onError obs error)
(.onCompleted obs))
(.addEventListener
xhr "load"
(fn []
(.onNext obs (.-response xhr))
(.onCompleted obs))
(.send xhr)))))))
(def users-url "https://api.github.com/users")
(def users-url "output.json")
(defn $ [sel] (.querySelector js/document sel))
(defn random-page []
(let [off (->> (.random js/Math) (* 500) (.floor js/Math))]
(+ users-url "?since=" off)))
(defn get-el [num] ($ (string/join ["#sugg-" num])))
(defn hide-el [num]
(let [el (get-el num)]
(set! (.-innerHTML el) "")))
(defn show-user [user num]
(let [el (get-el num)]
(set!
(.-innerHTML el)
(string/join
["<img src='" (.-avatar_url user) "'/>"
"<a href='" (.-html_url user) "'>"
(.-login user)
"</a>"]))))
(defn rand-user [users]
(aget users
(->> (count users)
(* (.random js/Math))
(.floor js/Math))))
(defn rand-suggester [closer response refresh]
(-> closer
(.startWith "startup click")
(.combineLatest response #(rand-user %2))
(.merge (.map refresh (fn [] nil)))
(.startWith nil)))
(defn render-suggester [suggester num]
(.subscribe
suggester
(fn [user]
(if (nil? user)
(hide-el num)
(show-user user num)))))
(defn click-stream [selector]
(.fromEvent js/Rx.Observable ($ selector) "click"))
(defn closer [num]
(click-stream (+ "#close-" num)))
(def refresh-stream (click-stream "#refresh"))
(def reqs
(-> refresh-stream
(.startWith "startup click")
(.map random-page)))
(def resp
(-> reqs
(.flatMap ajax)
(.share)))
(render-suggester
(rand-suggester (closer 1) resp refresh-stream) 1)
(render-suggester
(rand-suggester (closer 2) resp refresh-stream) 2)
(render-suggester
(rand-suggester (closer 3) resp refresh-stream) 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment