Skip to content

Instantly share code, notes, and snippets.

@retrogradeorbit
Created August 1, 2020 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retrogradeorbit/85ea0fffb47f4c69a0d56b4a193650d6 to your computer and use it in GitHub Desktop.
Save retrogradeorbit/85ea0fffb47f4c69a0d56b4a193650d6 to your computer and use it in GitHub Desktop.
split-camel-case using sequences vs using loop/recur
(defn split-camel-case-seq [s]
(let [parts (string/split s #"[a-z][A-Z]")
word-char-counts (-> (mapv #(+ 2 (count %)) parts)
(update 0 dec))
split-points (reductions + 0 word-char-counts)
from-to (map vector split-points (rest split-points))]
(map
(fn [[from to]] (subs s from (min to (count s))))
from-to)))
(defn split-camel-case-loop [s]
(loop [[a b & r] (seq s)
word ""
output []]
(if a
(if (and (re-matches #"[a-z]" (str a))
(re-matches #"[A-Z]" (str b)))
(recur (cons b r) "" (conj output (str word a)))
(recur (cons b r) (str word a) output))
(conj output word))))
#_ (= (split-camel-case-seq "CamelCaseToSplit")
(split-camel-case-loop "CamelCaseToSplit")
["Camel" "Case" "To" "Split"]
)
@retrogradeorbit
Copy link
Author

(re-seq #"[A-Z][a-z]+" "CamelCaseToSplit")

https://twitter.com/serioga/status/1289621101371256832?s=20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment