In Clojure Java interop gives us .indexOf
, but ClojureScript doesn't have that. How do I get the index of an item in a vector?
(def items [:a :b :c])
;; Clojure
(.indexOf items :a) ; => 0
;; ClojureScript
;; ???
Here is an explicitly recursive answer. I am hoping for a better answer though!
(defn index-of [s v]
(loop [idx 0 items s]
(cond
(empty? items) nil
(= v (first items)) idx
:else (recur (inc idx) (rest items)))))
Convert the vector into an array. http://clojuredocs.org/clojure_core/clojure.core/to-array
I'm unsure of what the perf is on this. :)
cljs.user=> (.indexOf (to-array [:a :b]) :b)
=> 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With