8000 Add some string utilities. · repos-javascript-compilers/wisp@20c191b · GitHub
[go: up one dir, main page]

Skip to content

Commit 20c191b

Browse files
committed
Add some string utilities.
1 parent 5b589fe commit 20c191b

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

src/string.wisp

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
(ns wisp.string
2-
(:require [wisp.runtime :refer [str subs re-matches nil? string?]]
2+
(:require [wisp.runtime :refer [str subs re-matches nil? string? re-pattern?]]
33
[wisp.sequence :refer [vec empty?]]))
44

55
(defn split
@@ -8,6 +8,11 @@
88
[string pattern limit]
99
(.split string pattern limit))
1010

11+
(defn split-lines
12+
"Splits s on \n or \r\n."
13+
[s]
14+
(split s #"\n|\r\n"))
15+
1116
(defn join
1217
"Returns a string of all elements in coll, as returned by (seq coll),
1318
separated by an optional separator."
@@ -40,6 +45,23 @@
4045
(str (upper-case (subs s 0 1))
4146
(lower-case (subs s 1)))))
4247

48+
(def ^:private ESCAPE_PATTERN
49+
(RegExp. "([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])" "g"))
50+
51+
(defn pattern-escape
52+
[source]
53+
(.replace (.replace source ESCAPE_PATTERN "\\$1")
54+
(RegExp. "\\x08" "g"), "\\x08"))
55+
56+
(defn replace-first
57+
"Replaces the first instance of match with replacement in s.
58+
match/replacement can be:
59+
60+
string / string
61+
pattern / (string or function of match)."
62+
[string match replacement]
63+
(.replace string match replacement))
64+
4365
(defn replace
4466
"Replaces all instance of match with replacement in s.
4567
@@ -51,7 +73,14 @@
5173
5274
See also replace-first."
5375
[string match replacement]
54-
(.replace string match replacement))
76+
(cond (string? match)
77+
(replace string (RegExp. pattern-escape match) "g" replacement)
78+
79+
(re-pattern? match)
80+
(.replace s (RegExp. (.-source match) "g") replacement)
81+
82+
:else
83+
(throw (str "Invalid match arg: " match))))
5584

5685

5786
;(def **WHITESPACE** (str "[\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000"
@@ -97,3 +126,8 @@
97126
(or (nil? string)
98127
(empty? string)
99128
(re-matches **SPACES** string)))
129+
130+
(defn reverse
131+
"Returns s with its characters reversed."
132+
[string]
133+
(join "" (.reverse (split string ""))))

0 commit comments

Comments
 (0)
0