Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index of vector in ClojureScript

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
;; ???
like image 832
Johanna Larsson Avatar asked Aug 15 '14 09:08

Johanna Larsson


2 Answers

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)))))
like image 143
Johanna Larsson Avatar answered Sep 29 '22 03:09

Johanna Larsson


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
like image 32
Trevor Avatar answered Sep 29 '22 02:09

Trevor