Skip to content

Instantly share code, notes, and snippets.

@zoren
Last active November 20, 2021 19:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoren/b72b18c78161b3d9066c0f968c63dc9d to your computer and use it in GitHub Desktop.
Save zoren/b72b18c78161b3d9066c0f968c63dc9d to your computer and use it in GitHub Desktop.
(defn index-of-safe
"Return index of value (string or char) in s, optionally searching
forward from from-index. Return nil if value not found.
Works around https://bugs.openjdk.java.net/browse/JDK-8027640
so the returned index is always greater equal to from-index.
This also works around JavaScript's similar behavior."
[s value from-index]
(if (< (count s) from-index)
nil
(clojure.string/index-of s value from-index)))
(defn indices-of
"Return indices of value (string or char) in s, optionally searching
forward from from-index. Return [] if value not found."
([s value] (indices-of s value 0))
([s value from-index]
(loop [index from-index
result []]
(if-let [new-index (index-of-safe s value index)]
(recur (inc new-index) (conj result new-index))
result))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment