Last active
March 5, 2017 12:30
-
-
Save jdubie/c8b62e24f7072078abc3 to your computer and use it in GitHub Desktop.
ClojureScript macros.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; nice for reagent | |
(defmacro defc | |
"syntactic sugar for declaring stateful components. Keeps signature of inner | |
and outer params consistent. | |
Before: | |
(defn stateful-component | |
[params] | |
(let [local state] | |
(fn [params]) | |
body))) | |
After: | |
(defc stateful-component | |
[params] | |
[local state] | |
body)" | |
[component-name params let-block & body] | |
(let [inner (concat `(fn ~params) body)] | |
`(def ~component-name (fn ~params | |
(let ~let-block ~inner))))) | |
;; generally useful | |
(defmacro mirror | |
"shorthand for declaring a map where the keys are keywords that correspond to | |
the value names. CoffeeScript users might find this as familiar shorthand. | |
Before: | |
{:foo foo :bar bar} | |
After: | |
(mirror foo bar)" | |
[& syms] | |
(apply hash-map (flatten (map (fn [s] [(keyword s) s]) syms)))) | |
(defmacro defm | |
"shorthand for defining referentially transparent functions. use in place of | |
`defn` for referentially transparent functions. | |
(defm add | |
[x y] | |
(+ x Y)" | |
[fn-name params & body] | |
(let [inner (concat `(fn ~params) body)] | |
`(def ~fn-name (memoize ~inner)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment