@@ -74,21 +74,21 @@ defmodule String do
74
74
be avoided in favor of binary functions or pattern matching.
75
75
For example, imagine you have a string `prefix` and you want to
76
76
remove this prefix from another string named `full`.
77
-
77
+
78
78
One may be tempted to write:
79
-
79
+
80
80
iex> take_prefix = fn full, prefix ->
81
81
...> base = String.length(prefix)
82
82
...> String.slice(full, base, String.length(full) - base)
83
83
...> end
84
84
...> take_prefix.("Mr. John", "Mr. ")
85
85
"John"
86
-
86
+
87
87
Although the function above works, it performs poorly. To
88
88
calculate the length of the string, we need to traverse it
89
89
fully, so we traverse both `prefix` and `full` strings, then
90
90
slice the `full` one, traversing it again.
91
-
91
+
92
92
A first attempting at improving it could be with ranges:
93
93
94
94
iex> take_prefix = fn full, prefix ->
@@ -103,7 +103,7 @@ defmodule String do
103
103
extract a substring from a string, we can use `byte_size/1`
104
104
and `binary_part/3` as there is no chance we will slice in
105
105
the middle of a codepoint made of more than one byte:
106
-
106
+
107
107
iex> take_prefix = fn full, prefix ->
108
108
...> base = byte_size(prefix)
109
109
...> binary_part(full, base, byte_size(full) - base)
@@ -112,7 +112,7 @@ defmodule String do
112
112
"John"
113
113
114
114
Or simply used pattern matching:
115
-
115
+
116
116
iex> take_prefix = fn full, prefix ->
117
117
...> base = byte_size(prefix)
118
118
...> <<_ :: binary-size(base), rest :: binary>> = full
@@ -672,8 +672,8 @@ defmodule String do
672
672
"a[,,]b[,,]c"
673
673
674
674
"""
675
- @ spec replace ( t , t , t ) :: t
676
- @ spec replace ( t , t , t , Keyword . t ) :: t
675
+ @ spec replace ( t , t | Regex . t , t ) :: t
676
+ @ spec replace ( t , t | Regex . t , t , Keyword . t ) :: t
677
677
678
678
def replace ( subject , pattern , replacement , options \\ [ ] ) when is_binary ( replacement ) do
679
679
if Regex . regex? ( pattern ) do
0 commit comments