Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@niwinz
Forked from rauhs/for-like-macros.cljs
Created March 28, 2017 07:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niwinz/295f5568fdf848718bd6a230d7a9807f to your computer and use it in GitHub Desktop.
Save niwinz/295f5568fdf848718bd6a230d7a9807f to your computer and use it in GitHub Desktop.
(defmacro afor
"Like for but eagerly builds a JS array.
Usually for react consumption."
[[item coll] & body]
`(let [coll# ~coll
neue# (cljs.core/array)]
(loop [xs# coll#
idx# 0]
(let [f-item# (first xs#)]
(when-some [~item f-item#]
(.push neue# (do ~@body))
(recur (next xs#) (inc idx#)))))
(seq neue#)))
(defmacro arfor
"Like afor but also compiles the body's hiccup.
(arfor [item items]
[:div {} item])"
[[item coll] & body]
`(let [coll# ~coll
neue# (cljs.core/array)]
(loop [xs# coll#
idx# 0]
(when-some [~item (first xs#)]
(.push neue# (html ~@body))
(recur (next xs#) (inc idx#))))
(seq neue#)))
(defmacro arifor
"Like arfor also gives the index. Syntax is like this to allow cursive to give variable
highlighting
(arifor [item items
idx _]
[:div {} idx \":\" item])"
[[item coll idx _] & body]
`(let [coll# ~coll
len# (count coll#)
neue# (cljs.core/make-array len#)]
(loop [xs# coll#
idx# 0]
(let [f-item# (first xs#)
~item f-item#
~idx idx#]
(when (some? f-item#)
(aset neue# idx# (html ~@body))
(recur (next xs#) (inc idx#)))))
(seq neue#)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment