Skip to content

add slice #104

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Mar 30, 2018
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
7 changes: 7 additions & 0 deletions test/Test/Data/String.purs
Original file line number Diff line number Diff line change
Expand Up @@ -206,3 +206,10 @@ 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