ClojureScript Vector Index

In Clojure, Java interop gives us .indexOf , but ClojureScript does not. How to get the index of an element in a vector?

 (def items [:a :b :c]) ;; Clojure (.indexOf items :a) ; => 0 ;; ClojureScript ;; ??? 
+5
source share
4 answers

Convert a vector to an array. http://clojuredocs.org/clojure_core/clojure.core/to-array

I'm not sure what perception is. :)

 cljs.user=> (.indexOf (to-array [:a :b]) :b) => 1 
+5
source

Here is the explicit recursive answer. I hope for a better answer though!

 (defn index-of [sv] (loop [idx 0 items s] (cond (empty? items) nil (= v (first items)) idx :else (recur (inc idx) (rest items))))) 
+4
source

Clojurescript does not seem to have an explicit index-of method (at least not the one I can find with a reasonable amount of search queries).

As an example, you can map clojurescript data structures to javascript arrays and use your own javascript .indexOf

 => (.indexOf (clj->js [:a :b :c :d]) (clj->js :c)) => 2 

But there are two problems with this: first, you have to leave the world of persistent data structures, which is a big part of what makes clojurescript great, but the big problem is that it does not work in reference types. For instance.

 => (.indexOf (clj->js [{:a :b} {:c :d}]) (clj->js {:c :d})) => -1 

therefore it is of limited use.

Your own recursive solution is perfect in the circumstances. If you want something more functional, you can do:

 (defn index-of [coll v] (let [i (count (take-while #(not= v %) coll))] (when (or (< i (count coll)) (= v (last coll))) i))) 
+3
source

another option (return nil if not-found)

 (defn index-of [coll value] (some (fn [[idx item]] (if (= value item) idx)) (map-indexed vector coll))) 
+3
source

Source: https://habr.com/ru/post/1200395/


All Articles