Skip to content

Commit

Permalink
Merge pull request #104 from themattchan/master
Browse files Browse the repository at this point in the history
add slice
  • Loading branch information
garyb authored Mar 30, 2018
2 parents bdf8c1b + e2d4b1d commit 6fce657
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Data/String.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,14 @@ exports.drop = function (n) {
};
};

exports._slice = function (b) {
return function (e) {
return function (s) {
return s.slice(b,e);
};
};
};

exports.count = function (p) {
return function (s) {
var i = 0;
Expand Down
28 changes: 28 additions & 0 deletions src/Data/String.purs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ module Data.String
, drop
, dropRight
, dropWhile
, slice
, stripPrefix
, stripSuffix
, count
Expand Down Expand Up @@ -172,6 +173,33 @@ takeWhile p s = take (count p s) s
dropWhile :: (Char -> Boolean) -> String -> String
dropWhile p s = drop (count p s) s

-- | Returns the substring at indices `[begin, end)`.
-- | If either index is negative, it is normalised to `length s - index`,
-- | where `s` is the input string. `Nothing` is returned if either
-- | index is out of bounds or if `begin > end` after normalisation.
-- |
-- | ```purescript
-- | slice 0 0 "purescript" == Just ""
-- | slice 0 1 "purescript" == Just "p"
-- | slice 3 6 "purescript" == Just "esc"
-- | slice (-4) (-1) "purescript" == Just "rip"
-- | slice (-4) 3 "purescript" == Nothing
-- | ```
slice :: Int -> Int -> String -> Maybe String
slice b e s = if b' < 0 || b' >= l ||
e' < 0 || e' >= l ||
b' > e'
then Nothing
else Just (_slice b e s)
where
l = length s
norm x | x < 0 = l + x
| otherwise = x
b' = norm b
e' = norm e

foreign import _slice :: Int -> Int -> String -> String

-- | If the string starts with the given prefix, return the portion of the
-- | string left after removing it, as a Just value. Otherwise, return Nothing.
-- |
Expand Down
11 changes: 11 additions & 0 deletions test/Test/Data/String.purs
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,14 @@ testString = do
assert $ joinWith "" [] == ""
assert $ joinWith "" ["a", "b"] == "ab"
assert $ joinWith "--" ["a", "b", "c"] == "a--b--c"

log "slice"
assert $ slice 0 0 "purescript" == Just ""
assert $ slice 0 1 "purescript" == Just "p"
assert $ slice 3 6 "purescript" == Just "esc"
assert $ slice (-4) (-1) "purescript" == Just "rip"
assert $ slice (-4) 3 "purescript" == Nothing -- b' > e'
assert $ slice 1000 3 "purescript" == Nothing -- b' > e' (subsumes b > l)
assert $ slice 2 (-15) "purescript" == Nothing -- e' < 0
assert $ slice (-15) 9 "purescript" == Nothing -- b' < 0
assert $ slice 3 1000 "purescript" == Nothing -- e > l

0 comments on commit 6fce657

Please sign in to comment.