medley icon indicating copy to clipboard operation
medley copied to clipboard

Suggested addition: index-of

Open orestis opened this issue 4 years ago • 3 comments

The humble indexOf -> you have a known small vector or sequence, you are doing ops on it and you want to find a particular element's index. (Because you have to e.g. replace it later, or put something before or after it).

Naive implementation:

(defn index-of
  "Return the first index of x inside a seq of xs, or nil"
  [xs x]
  (->> xs
       (medley/indexed)
       (medley/find-first (fn [[_idx item]]
                            (= item x)))
       (first)))

orestis avatar Jun 08 '21 11:06 orestis

If you already have a vector, you can just use .indexOf in the implementation, for performance.

borkdude avatar Jun 08 '21 11:06 borkdude

True, if you know what you have. But .indexOf will also use identical? instead of =, right? This might be a reason to add this more generic index-of -- if someone needs absolute performance they would stick with vectors and use .indexOf. In any case, this is more a convenience (for me) when manipulating very small vectors (e.g. up to 10 items)

orestis avatar Jun 08 '21 11:06 orestis

@orestis I don't think it does:

https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/APersistentVector.java#L186-L191

I mean, if you're going to implement this as part of this library, it's fairly cheap to check vector? first and then call this, and for other cases fall back on the seq behavior.

borkdude avatar Jun 08 '21 11:06 borkdude