| 1 |
(ns ^:no-doc camel-snake-kebab.internals.string-separator |
| 2 |
(:require [clojure.string :as string]) |
| 3 |
#?(:clj (:import (java.util.regex Pattern)))) |
| 4 |
|
| 5 |
#?(:clj (set! *warn-on-reflection* true)) |
| 6 |
|
| 7 |
(defprotocol StringSeparator |
| 8 |
(split [this s] ": StringSeparator -> String -> NonEmptySeq[String]")) |
| 9 |
|
| 10 |
#?(:clj |
| 11 |
(letfn [(split-by-pattern [^Pattern p, ^String s] |
| 12 |
(string/split s p)) |
| 13 |
;; These could be optimized e.g. by using StringUtils in Apache Commons: |
| 14 |
(split-by-string [^String p, ^String s] |
| 15 |
(split-by-pattern (-> p Pattern/quote Pattern/compile) s)) |
| 16 |
(split-by-char [^Character p, ^String s] |
| 17 |
(split-by-string (String/valueOf p) s))] |
| 18 |
(extend Pattern StringSeparator {:split split-by-pattern}) |
| 19 |
(extend String StringSeparator {:split split-by-string}) |
| 20 |
(extend Character StringSeparator {:split split-by-char})) |
| 21 |
|
| 22 |
:cljs |
| 23 |
(extend-protocol StringSeparator |
| 24 |
;; Notes: |
| 25 |
;; * Characters are just strings in ClojureScript. |
| 26 |
;; * Using js/RegExp generates a warning, but what's the right way? |
| 27 |
|
| 28 |
js/RegExp |
| 29 |
(split [this s] (string/split s this)) |
| 30 |
|
| 31 |
string |
| 32 |
(split [this s] (string/split s this)))) |
| 33 |
|
| 34 |
(defn classify-char [c] |
| 35 |
(case c |
| 36 |
(\0 \1 \2 \3 \4 \5 \6 \7 \8 \9) :number |
| 37 |
(\- \_ \space \tab \newline \o013 \formfeed \return) :whitespace |
| 38 |
(\a \b \c \d \e \f \g \h \i \j \k \l \m \n \o \p \q \r \s \t \u \v \w \x \y \z) :lower |
| 39 |
(\A \B \C \D \E \F \G \H \I \J \K \L \M \N \O \P \Q \R \S \T \U \V \W \X \Y \Z) :upper |
| 40 |
:other)) |
| 41 |
|
| 42 |
(defn generic-split [ss] |
| 43 |
(let [cs (mapv classify-char ss) |
| 44 |
ss-length #?(:clj (.length ^String ss) |
| 45 |
:cljs (.-length ss))] |
| 46 |
(loop [result (transient []), start 0, current 0] |
| 47 |
(let [next (inc current) |
| 48 |
result+new (fn [end] |
| 49 |
(if (> end start) |
| 50 |
(conj! result (.substring ^String ss start end)) |
| 51 |
result))] |
| 52 |
(cond (>= current ss-length) |
| 53 |
(or (seq (persistent! (result+new current))) |
| 54 |
;; Return this instead of an empty seq: |
| 55 |
[""]) |
| 56 |
|
| 57 |
(= (nth cs current) :whitespace) |
| 58 |
(recur (result+new current) next next) |
| 59 |
|
| 60 |
(let [[a b c] (subvec cs current)] |
| 61 |
;; This expression is not pretty, |
| 62 |
;; but it compiles down to sane JavaScript. |
| 63 |
(or (and (not= a :upper) (= b :upper)) |
| 64 |
(and (not= a :number) (= b :number)) |
| 65 |
(and (= a :upper) (= b :upper) (= c :lower)))) |
| 66 |
(recur (result+new next) next next) |
| 67 |
|
| 68 |
:else |
| 69 |
(recur result start next)))))) |
| 70 |
|
| 71 |
(def generic-separator |
| 72 |
(reify StringSeparator |
| 73 |
(split [_ s] (generic-split s)))) |