Skip to content

Commit

Permalink
Merge pull request #13 from adrian17/master
Browse files Browse the repository at this point in the history
implemented last_option
  • Loading branch information
EntilZha committed Mar 14, 2015
2 parents 8df89f2 + cb1afa8 commit d7277f5
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@ seq([1, 2, 3])[-1]

## List of supported functions
### List to List
* init: get everything except last element
* tail: get everything except first element
* inits: get subsequent inits
* tails: get subsequent tails
* drop: drop first n elements
* drop_while: drop first elements using f
* take: take first n elements
Expand All @@ -96,6 +99,7 @@ seq([1, 2, 3])[-1]
* head, first: get first element
* head_option: get first element or None
* last: get last element
* last_option: get last element or None
* reduce: reduce sequence using f
* fold_left
* fold_right
Expand Down
14 changes: 14 additions & 0 deletions functional/chain.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,20 @@ def last(self):
"""
return _wrap(self.sequence[-1])

def last_option(self):
"""
Returns the last element of the sequence or None, if the sequence is empty.
>>> seq([1, 2, 3]).last_option()
3
>>> seq([]).last_option()
None
"""
if not self.sequence:
return None
return self.last()

def init(self):
"""
Returns the sequence, without its last element.
Expand Down
9 changes: 9 additions & 0 deletions test/test_functional.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,15 @@ def test_last(self):
self.assertEqual(l.last(), [3, 4])
self.assertType(l.last())

def test_last_option(self):
l = seq([1, 2, 3])
self.assertEqual(l.last_option(), 3)
l = seq([1, 2, [3, 4]])
self.assertEqual(l.last_option(), [3, 4])
self.assertType(l.last_option())
l = seq([])
self.assertIsNone(l.last_option())

def test_init(self):
l = seq([1, 2, 3, 4])
expect = [1, 2, 3]
Expand Down

0 comments on commit d7277f5

Please sign in to comment.