Skip to content

Commit f4427c7

Browse files
David Liebke and Stuart Hallowaystuarthalloway
authored andcommitted
collapse the replace-first-* fns, align arg order with clojure convention
Signed-off-by: Stuart Halloway <[email protected]>
1 parent 8efeb01 commit f4427c7

2 files changed

Lines changed: 18 additions & 14 deletions

File tree

src/clj/clojure/string.clj

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -45,20 +45,10 @@
4545
(replace-by s match replacement))
4646
:default (throw (IllegalArgumentException. (str "Invalid match arg: " match)))))
4747

48-
(defn replace-first-str
49-
"Replace first occurance of substring a with b in s."
50-
[^String a ^String b ^String s]
51-
(.replaceFirst (re-matcher (Pattern/quote a) s) b))
52-
53-
(defn replace-first-re
54-
"Replace first match of re in s."
55-
[^Pattern re ^String replacement ^String s]
56-
(.replaceFirst (re-matcher re s) replacement))
57-
58-
(defn replace-first-by
48+
(defn- replace-first-by
5949
"Replace first match of re in s with the result of
6050
(f (re-groups the-match))."
61-
[^Pattern re f ^String s]
51+
[^String s ^Pattern re f]
6252
(let [m (re-matcher re s)]
6353
(let [buffer (StringBuffer.)]
6454
(if (.find m)
@@ -67,6 +57,19 @@
6757
(.appendTail m buffer)
6858
(str buffer))))))
6959

60+
(defn replace-first
61+
""
62+
[^String s match replacement]
63+
(cond
64+
(instance? String match)
65+
(.replaceFirst s (Pattern/quote ^String match) ^String replacement)
66+
(instance? Pattern match)
67+
(if (string? replacement)
68+
(.replaceFirst (re-matcher ^Pattern match s) ^String replacement)
69+
(replace-first-by s match replacement))
70+
:default (throw (IllegalArgumentException. (str "Invalid match arg: " match)))))
71+
72+
7073
(defn ^String join
7174
"Returns a string of all elements in coll, separated by
7275
separator. Like Perl's join."

test/clojure/test_clojure/string.clj

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,9 @@
1111
(is (= "FOObarFOO" (s/replace "foobarfoo" #"foo" s/upper-case))))
1212

1313
(deftest t-replace-first
14-
(is (= "barbarfoo" (s/replace-first-re #"foo" "bar" "foobarfoo")))
15-
(is (= "FOObarfoo" (s/replace-first-by #"foo" s/upper-case "foobarfoo"))))
14+
(is (= "barbarfoo" (s/replace-first "foobarfoo" "foo" "bar")))
15+
(is (= "barbarfoo" (s/replace-first "foobarfoo" #"foo" "bar")))
16+
(is (= "FOObarfoo" (s/replace-first "foobarfoo" #"foo" s/upper-case))))
1617

1718
(deftest t-join
1819
(are [x coll] (= x (s/join coll))

0 commit comments

Comments
 (0)