Skip to content

Commit 05305ea

Browse files
committed
check bounds etc
1 parent 5849257 commit 05305ea

File tree

3 files changed

+17
-5
lines changed

3 files changed

+17
-5
lines changed

src/Data/String.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,8 +136,12 @@ exports._slice = function (just) {
136136
return function (b) {
137137
return function (e) {
138138
return function (s) {
139-
var res = s.slice(b, e);
140-
return res.length === 0 ? nothing : just(res);
139+
var b1 = b < 0 ? s.length + b : b;
140+
var e1 = e < 0 ? s.length + e : e;
141+
if ( b1 < 0 || e1 >= s.length || b1 > e1 )
142+
return nothing;
143+
else
144+
return just(s.slice(b,e));
141145
};
142146
};
143147
};

src/Data/String.purs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -179,10 +179,11 @@ dropWhile p s = drop (count p s) s
179179
-- | index is out of bounds or if `begin > end` after normalisation.
180180
-- |
181181
-- | ```purescript
182+
-- | slice 0 0 "purescript" == Just ""
182183
-- | slice 0 1 "purescript" == Just "p"
183-
-- | slice 3 6 "purescript" == Just "ecr"
184-
-- | slice -4 -1 "purescript" == Just "rip"
185-
-- | slice -4 3 "purescript" == Nothing
184+
-- | slice 3 6 "purescript" == Just "esc"
185+
-- | slice (-4) (-1) "purescript" == Just "rip"
186+
-- | slice (-4) 3 "purescript" == Nothing
186187
-- | ```
187188
slice :: Int -> Int -> String -> Maybe String
188189
slice = _slice Just Nothing

test/Test/Data/String.purs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -206,3 +206,10 @@ testString = do
206206
assert $ joinWith "" [] == ""
207207
assert $ joinWith "" ["a", "b"] == "ab"
208208
assert $ joinWith "--" ["a", "b", "c"] == "a--b--c"
209+
210+
log "slice"
211+
assert $ slice 0 0 "purescript" == Just ""
212+
assert $ slice 0 1 "purescript" == Just "p"
213+
assert $ slice 3 6 "purescript" == Just "esc"
214+
assert $ slice (-4) (-1) "purescript" == Just "rip"
215+
assert $ slice (-4) 3 "purescript" == Nothing

0 commit comments

Comments
 (0)