Last active
December 7, 2017 00:27
-
-
Save anthonyjb/9e67f7816f5e94ef627df43af842cbd3 to your computer and use it in GitHub Desktop.
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
# Prerequisites: | |
# | |
# - Using Python 3.5+ | |
# - Install manhattan-chains (`pip install manhattan-chains`) | |
# | |
from manhattan.chains import Chain | |
# Define link factories | |
def make_name_unique(template='{0}-{1}'): | |
def make_name_unique(state): | |
i = 1 | |
while state.list_name in state.lists: | |
state.list_name = template.format(state.list_name, i) | |
return make_name_unique | |
# Define the chains | |
# Show the list | |
show = Chain([ | |
'get_list', | |
'render_list' | |
]) | |
@show.link | |
def get_list(state): | |
if state.args[0] not in state.lists: | |
return 'List not found: ' + state.args[0] | |
state.list_name = state.args[0] | |
state.list = state.lists[state.list_name] | |
@show.link | |
def render_list(state): | |
lines = [state.list_name, '-' * len(state.list_name)] | |
lines += ['- ' + item for item in state.list] | |
return '\n' + '\n'.join(lines) + '\n' | |
# Add an item to the list | |
add = Chain([ | |
'get_list', | |
'add_item', | |
'render_list' | |
]) | |
add.set_link(get_list) | |
add.set_link(render_list) | |
@add.link | |
def add_item(state): | |
state.list.append(state.args[1]) | |
# Add a new list | |
new = Chain([ | |
'is_name_unique', | |
[ | |
[ | |
'add_list', | |
'render_list' | |
], | |
[ | |
'make_name_unique', | |
'add_list', | |
'render_list' | |
] | |
] | |
]) | |
new.set_link(render_list) | |
new.set_link(make_name_unique('{0} ** ({1})')) | |
@new.link | |
def is_name_unique(state): | |
state.list_name = state.args[0] | |
return state.list_name not in state.lists | |
@new.link | |
def add_list(state): | |
state.lists[state.list_name] = [] | |
state.list = state.lists[state.list_name] | |
# Modify the chains behaviour to simply overwrite any existing list | |
new.update([ | |
'set_list_name', | |
'add_list', | |
'render_list' | |
]) | |
@new.link | |
def set_list_name(state): | |
state.list_name = state.args[0] | |
# Define a table of lists | |
lists = { | |
'shopping': ['milk', 'eggs'], | |
'todo': ['take dog to groomers'] | |
} | |
# Define a table of actions the user can perform | |
actions = { | |
'add': add, | |
'new': new, | |
'show': show | |
} | |
# Parse the users commands | |
while True: | |
user_input = input('? ') | |
[action, *args] = user_input.split(' ') | |
if action == 'quit': | |
break | |
elif action in actions: | |
output = actions[action](lists=lists, args=args) | |
print(output) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment