mardi 30 décembre 2014

Using higher order functions to apply a filter?



if user_filter:
for each in something:
if filter_condition_met:
do_something(each)

else:
for each in something:
do_something(each)


Here I am repeating the entire code again which is against DRY principles.



for each in something:
if user_filter:
if not filter_condition_met:
continue
do_something(each)


Here I am doing the filter check for all items in the loop, while essentially it needs to be done just once.


Can I use higher order functions to check the filter condition once and generate a code that does the job? It looks like a filter and then transform operation. Can someone give some ideas?





Aucun commentaire:

Enregistrer un commentaire