Skip to content

Commit 1c518db

Browse files
committed
move bounds checking logic to purescript
1 parent 31b21bb commit 1c518db

File tree

2 files changed

+17
-22
lines changed

2 files changed

+17
-22
lines changed

src/Data/String.js

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -131,22 +131,10 @@ exports.drop = function (n) {
131131
};
132132
};
133133

134-
exports._slice = function (just) {
135-
return function (nothing) {
136-
return function (b) {
137-
return function (e) {
138-
return function (s) {
139-
var b1 = b < 0 ? s.length + b : b;
140-
var e1 = e < 0 ? s.length + e : e;
141-
if ( b1 < 0 || b1 >= s.length
142-
|| e1 < 0 || e1 >= s.length
143-
|| b1 > e1
144-
)
145-
return nothing;
146-
else
147-
return just(s.slice(b,e));
148-
};
149-
};
134+
exports._slice = function (b) {
135+
return function (e) {
136+
return function (s) {
137+
return s.slice(b,e);
150138
};
151139
};
152140
};

src/Data/String.purs

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -186,12 +186,19 @@ dropWhile p s = drop (count p s) s
186186
-- | slice (-4) 3 "purescript" == Nothing
187187
-- | ```
188188
slice :: Int -> Int -> String -> Maybe String
189-
slice = _slice Just Nothing
190-
191-
foreign import _slice
192-
:: (forall a. a -> Maybe a)
193-
-> (forall a. Maybe a)
194-
-> Int -> Int -> String -> Maybe String
189+
slice b e s = if b' < 0 || b' >= l ||
190+
e' < 0 || e' >= l ||
191+
b' > e'
192+
then Nothing
193+
else Just (_slice b e s)
194+
where
195+
l = length s
196+
norm x | x < 0 = l + x
197+
| otherwise = x
198+
b' = norm b
199+
e' = norm e
200+
201+
foreign import _slice :: Int -> Int -> String -> String
195202

196203
-- | If the string starts with the given prefix, return the portion of the
197204
-- | string left after removing it, as a Just value. Otherwise, return Nothing.

0 commit comments

Comments
 (0)