Simplify the fvar macro

This commit is contained in:
Dan Holmsand 2014-04-01 15:17:33 +02:00
parent 9fee64b1bf
commit 4060bfc6fe
2 changed files with 31 additions and 67 deletions

View File

@ -49,32 +49,30 @@
`(aset ~object ~@names ~value)))
(defn- has-fvar [] *assert*)
(defmacro fvar
[f]
(assert (symbol? f))
(if-not (has-fvar)
f
(let [fref (str *ns* "/" f)]
`(let [f# (aget reagent.interop/fvars ~fref)]
(if-not (nil? f#)
f#
(do
(assert (not (nil? ~f))
~(str "undefined fn: " f))
(let [old# (aget ~f "-fvar")
v# (if (not (nil? old#))
old#
(doto #(.apply ~f nil (~'js* "arguments"))
(aset "name" (.-name ~f))
(aset "fvar" true)))]
(aset ~f "-fvar" v#)
(aset reagent.interop/fvars ~fref v#))))))))
(let [fns (or (namespace f)
(str *ns*))
fref (str *ns* "/" f)]
`(let [f# (aget reagent.interop/fvars ~fref)]
(if-not (nil? f#)
f#
(do
(assert (not (nil? ~f))
~(str "undefined fn: " f))
(assert (identical? ~f ~(symbol fns (name f)))
~(str "Not in a namespace: " f))
(let [old# (aget ~f "-fvar")
v# (if (not (nil? old#))
old#
(doto #(.apply ~f nil (~'js* "arguments"))
(aset "name" (.-name ~f))
(aset "fvar" true)))]
(aset ~f "-fvar" v#)
(aset reagent.interop/fvars ~fref v#)))))))
(defmacro fvar?
[f]
(if (has-fvar)
`(and (fn? ~f)
(not (nil? (aget ~f "fvar"))))
`(fn? f)))
`(and (fn? ~f)
(not (nil? (aget ~f "fvar")))))

View File

@ -1,48 +1,8 @@
(ns testinterop
(:require [cemerick.cljs.test :as t :refer-macros [is deftest]]
[reagent.debug :refer-macros [dbg]]
[reagent.interop :refer-macros [.' .! fvar fvar? oget oset odo]]))
[reagent.interop :refer-macros [.' .! fvar fvar?]]))
(deftest interop-basic
(let [o #js{:foo "foo"
:foobar #js{:bar "bar"}
:bar-foo "barfoo"}]
(is (= "foo" (oget o :foo)))
(is (= "bar" (oget o :foobar :bar)))
(is (= "barfoo" (oget o :bar-foo)))
(oset o :foo "foo1")
(is (= "foo1" (oget o :foo)))
(oset o :foo "foo2")
(is (= "foo2" (oget o :foo)))
(oset o :foobar :bar "bar1")
(is (= "bar1" (oget o :foobar :bar)))))
(deftest interop-call
(let [o #js{:bar "bar1"
:foo (fn [x]
(this-as this
(str x (oget this :bar))))}
o2 #js{:o o}]
(is (= "ybar1" (odo o :foo "y")))
(is (= "xxbar1" (odo o2 [:o :foo] "xx")))
(is (= "abar1" (-> o2
(oget :o :foo)
(odo [] "a"))))
(is (= "bar1" (odo o :foo)))
(is (= "bar1" (odo o [:foo])))
(is (= "bar1" (odo o2 [:o :foo])))
(oset o :bar "bar2")
(is (= "bar2" (odo o :foo)))
(is (= "1bar2" (odo (oget o :foo)
:call o 1)))
(is (= "yy" (odo identity [] "yy")))))
(deftest iterop-quote
(let [o #js{:foo "foo"
@ -92,12 +52,18 @@
(def f nil)
(deftest interop-fvar
(set! f (fn [] "foo"))
(set! f (fn [& args] (into ["foo"] args)))
(let [f' (fvar f)]
(is (= "foo" (f')))
(is (= ["foo"] (f')))
(is (= ["foo" 1] (f' 1)))
(is (= ["foo" 1 2] (f' 1 2)))
(is (= ["foo" 1 2 3] (f' 1 2 3)))
(set! f (fn [] "foobar"))
(is (= "foobar" (f')))
(is (identical? f' (fvar f)))))
(is (identical? f' (fvar f)))
(is (fvar? f'))
(is (not (fvar? f)))
(is (fn? f'))))