2

My friend showed me a blog post that makes use of ClojureScript macros and he claims that the code provided cannot be elegantly converted to JavaScript because of JavaScript's lack of macro support in the language. Specifically, the go macro in this code snippet is not possible in JavaScript

(def c (chan))

(defn render [q]
  (apply str
    (for [p (reverse q)]
      (str "<div class='proc-" p "'>Process " p "</div>"))))

(go (while true (<! (timeout 250)) (>! c 1)))
(go (while true (<! (timeout 1000)) (>! c 2)))
(go (while true (<! (timeout 1500)) (>! c 3)))

(defn peekn
  "Returns vector of (up to) n items from the end of vector v"
  [v n]
  (if (> (count v) n)
    (subvec v (- (count v) n))
    v))

(let [el  (by-id "ex0")
      out (by-id "ex0-out")]
  (go (loop [q []]
        (set-html! out (render q))
        (recur (-> (conj q (<! c)) (peekn 10))))))

Source: http://swannodette.github.io/2013/07/12/communicating-sequential-processes/

I'm a bit hesitant to believe that it cannot be done without some sort of macro library in an elegant way. I am not looking for a solution that does the same behavior in a different way (such as three infinite loops of setTimeout, etc.), but one that has the same "spirit" as the original.

2
  • Well you could always fire up a clojure script interpreter. Does that count as am "elegant" macro library?
    – Bergi
    Oct 28, 2015 at 2:19
  • 1
    You'll want to have a look at jlongster.com/…
    – Bergi
    Oct 28, 2015 at 2:23

1 Answer 1

5

From the same blog, only six weeks later:

Last night I expressed some frustration about the state and future of concurrency in JavaScript. I ended up having a little bit of back and forth with David Herman and he pointed out that ES6 Generators can express Go and core.async's flavor of CSP. […]

What follows is a minimal amount of code that works in Node.js 0.11 with the ES6 harmony command line setting. […] The insight is to combine Generators with Channels.

So yes, you'll need ES6 generators that can yield, and a CSP library (not built into JS), but then you'll have exactly the same spirit as the original.

If ES7 gets async/await syntax, you can also use a promise-based channel implementation and would be able to use an immediately-invoked asyncchronous function expression (IIAFE) instead of the go call. Also have a look over here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.