Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
65 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
# -*- coding: utf-8 -*- | ||
|
||
|
||
def dispatch(*funcs): | ||
'''Iterates through the functions | ||
and calls them with given the parameters | ||
and returns the first non-empty result | ||
>>> f = dispatch(lambda: None, lambda: 1) | ||
>>> f() | ||
1 | ||
:param \*funcs: funcs list of dispatched functions | ||
:returns: dispatch functoin | ||
''' | ||
|
||
def _dispatch(*args, **kwargs): | ||
for f in funcs: | ||
result = f(*args, **kwargs) | ||
if result is not None: | ||
return result | ||
return None | ||
|
||
return _dispatch |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
# -*- coding: utf-8 -*- | ||
|
||
from railroad import dispatch | ||
|
||
|
||
def test_return_none_if_all_functions_return_empty_result(): | ||
def empty(): | ||
return None | ||
|
||
dispatch_function = dispatch( | ||
empty, | ||
empty, | ||
empty, | ||
empty | ||
) | ||
|
||
assert dispatch_function() is None | ||
|
||
|
||
def test_return_first_non_empty_result(): | ||
def empty(): | ||
return None | ||
|
||
def one(): | ||
return 1 | ||
|
||
def two(): | ||
return 2 | ||
|
||
dispatch_function = dispatch( | ||
empty, | ||
empty, | ||
one, | ||
two, | ||
empty | ||
) | ||
|
||
assert dispatch_function() == 1 |