Skip to content

Commit

Permalink
dropEnd and takeEnd functions (#114)
Browse files Browse the repository at this point in the history
* add takeEnd and dropEnd functions with docs

* add tests

* change order of functions
  • Loading branch information
notgiorgi authored and paf31 committed Sep 5, 2017
1 parent b363605 commit e502257
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Data/Array.purs
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,10 @@ module Data.Array
, sortWith
, slice
, take
, takeEnd
, takeWhile
, drop
, dropEnd
, dropWhile
, span
, group
Expand Down Expand Up @@ -495,6 +497,11 @@ foreign import slice :: forall a. Int -> Int -> Array a -> Array a
-- | array.
foreign import take :: forall a. Int -> Array a -> Array a

-- | Keep only a number of elements from the end of an array, creating a new
-- | array.
takeEnd :: forall a. Int -> Array a -> Array a
takeEnd n xs = drop (length xs - n) xs

-- | Calculate the longest initial subarray for which all element satisfy the
-- | specified predicate, creating a new array.
takeWhile :: forall a. (a -> Boolean) -> Array a -> Array a
Expand All @@ -503,6 +510,10 @@ takeWhile p xs = (span p xs).init
-- | Drop a number of elements from the start of an array, creating a new array.
foreign import drop :: forall a. Int -> Array a -> Array a

-- | Drop a number of elements from the start of an array, creating a new array.
dropEnd :: forall a. Int -> Array a -> Array a
dropEnd n xs = take (length xs - n) xs

-- | Remove the longest initial subarray for which all element satisfy the
-- | specified predicate, creating a new array.
dropWhile :: forall a. (a -> Boolean) -> Array a -> Array a
Expand Down
10 changes: 10 additions & 0 deletions test/Test/Data/Array.purs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,11 @@ testArray = do
assert $ (A.takeWhile (_ /= 3) [1, 2, 3]) == [1, 2]
assert $ (A.takeWhile (_ /= 1) nil) == nil

log "take should keep the specified number of items from the end of an array, discarding the rest"
assert $ (A.takeEnd 1 [1, 2, 3]) == [3]
assert $ (A.takeEnd 2 [1, 2, 3]) == [2, 3]
assert $ (A.takeEnd 1 nil) == nil

log "drop should remove the specified number of items from the front of an array"
assert $ (A.drop 1 [1, 2, 3]) == [2, 3]
assert $ (A.drop 2 [1, 2, 3]) == [3]
Expand All @@ -261,6 +266,11 @@ testArray = do
assert $ (A.dropWhile (_ /= 2) [1, 2, 3]) == [2, 3]
assert $ (A.dropWhile (_ /= 1) nil) == nil

log "drop should remove the specified number of items from the end of an array"
assert $ (A.dropEnd 1 [1, 2, 3]) == [1, 2]
assert $ (A.dropEnd 2 [1, 2, 3]) == [1]
assert $ (A.dropEnd 1 nil) == nil

log "take and drop should treat negative arguments as zero"
assert $ (A.take (-2) [1, 2, 3]) == nil
assert $ (A.drop (-2) [1, 2, 3]) == [1, 2, 3]
Expand Down

0 comments on commit e502257

Please sign in to comment.