Last active
March 29, 2022 14:34
-
-
Save tgroshon/85ee4b24dec99b3865296acc4a6c78ac to your computer and use it in GitHub Desktop.
Because it can be done
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
from operator import itemgetter, eq | |
from functools import partial | |
""" | |
Find dictionary with ID = 2 in a functional way | |
""" | |
records = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}] | |
def compose(*funcs): | |
def h(*args, **kwargs): | |
first_run = True | |
last = None | |
for f in funcs: | |
if first_run: | |
last = f(*args, **kwargs) | |
first_run = False | |
else: | |
last = f(last) | |
return last | |
return h | |
id_equals_2 = partial(eq, 2) | |
get_id = itemgetter('id') | |
finder = compose(get_id, id_equals_2) | |
filtered_records = filter(finder, records) # Short version: filter(compose(itemgetter('id'), partial(eq, 2)), data) | |
# And WTF, can't call `[1,2].first()` or `[1,2].last()` and have them return item or None. | |
record = next(filtered_records) # returning an iterator is blah to ergonomics | |
assert records[1] == record, "Or else I'm dumb" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment