Skip to content

Commit

Permalink
Added dispatch function
Browse files Browse the repository at this point in the history
  • Loading branch information
s-m-i-t-a committed Nov 25, 2016
1 parent 3a13b0b commit ddb4afa
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 1 deletion.
4 changes: 3 additions & 1 deletion railroad/__init__.py
@@ -1,6 +1,6 @@
__author__ = 'Jindrich K. Smitka'
__email__ = 'smitka.j@gmail.com'
__version__ = '0.4.1'
__version__ = '0.5.0'

from .railroad import ( # noqa
prepare,
Expand All @@ -16,3 +16,5 @@
from .actions import actions, lift, result # noqa

from .guard import guard, GuardError # noqa

from .dispatch import dispatch # noqa
24 changes: 24 additions & 0 deletions railroad/dispatch.py
@@ -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
38 changes: 38 additions & 0 deletions test/test_dispatch.py
@@ -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

0 comments on commit ddb4afa

Please sign in to comment.