Skip to content

Commit 2e60399

Browse files
authored
Merge pull request purescript#65 from Risto-Stevcev/master
Added 'splitAt' function
2 parents b699746 + 8f1be34 commit 2e60399

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

src/Data/String.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,17 @@ exports.split = function (sep) {
139139
};
140140
};
141141

142+
exports._splitAt = function (just) {
143+
return function (nothing) {
144+
return function (i) {
145+
return function (s) {
146+
return i >= 0 && i < s.length ?
147+
just([s.substring(0, i), s.substring(i)]) : nothing;
148+
};
149+
};
150+
};
151+
};
152+
142153
exports.toCharArray = function (s) {
143154
return s.split("");
144155
};

src/Data/String.purs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ module Data.String
2525
, stripSuffix
2626
, count
2727
, split
28+
, splitAt
2829
, toCharArray
2930
, toLower
3031
, toUpper
@@ -197,6 +198,16 @@ foreign import count :: (Char -> Boolean) -> String -> Int
197198
-- | * `split " " "hello world" == ["hello", "world"]`
198199
foreign import split :: String -> String -> Array String
199200

201+
-- | Returns the substrings of split at the given index, if the index is within bounds.
202+
splitAt :: Int -> String -> Maybe (Array String)
203+
splitAt = _splitAt Just Nothing
204+
205+
foreign import _splitAt :: (forall a. a -> Maybe a)
206+
-> (forall a. Maybe a)
207+
-> Int
208+
-> String
209+
-> Maybe (Array String)
210+
200211
-- | Converts the string into an array of characters.
201212
foreign import toCharArray :: String -> Array Char
202213

test/Test/Data/String.purs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,13 @@ testString = do
155155
assert $ split "b" "aabcc" == ["aa", "cc"]
156156
assert $ split "d" "abc" == ["abc"]
157157

158+
log "splitAt"
159+
assert $ splitAt 1 "" == Nothing
160+
assert $ splitAt 0 "a" == Just ["", "a"]
161+
assert $ splitAt 1 "ab" == Just ["a", "b"]
162+
assert $ splitAt 3 "aabcc" == Just ["aab", "cc"]
163+
assert $ splitAt (-1) "abc" == Nothing
164+
158165
log "toCharArray"
159166
assert $ toCharArray "" == []
160167
assert $ toCharArray "a" == ['a']

0 commit comments

Comments
 (0)