Last active
March 2, 2018 12:29
-
-
Save bofm/df066df2176bbe69fc3e62e87e1afd1d to your computer and use it in GitHub Desktop.
It. A handy iterator with method chaining.
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
import itertools | |
import functools | |
class It: | |
"""A handy iterator with method chaining. | |
>>> It([1, 2, 3]).map(lambda x: x**2).filter(lambda x: x<5).chain_after('abc').apply(list) | |
['a', 'b', 'c', 1, 4] | |
""" | |
def __init__(self, iterable): | |
self._it = iter(iterable) | |
def __iter__(self): | |
return self._it | |
def reduce(self, fn, initializer=None): | |
if initializer is not None: | |
return functools.reduce(fn, self, initializer) | |
return functools.reduce(fn, self) | |
def map(self, *fns): | |
return It(fns).reduce(lambda it, fn: It(map(fn, it)), self) | |
def starmap(self, *fns): | |
return It(fns).reduce(lambda it, fn: It(itertools.starmap(fn, it)), self) | |
def filter(self, *fns): | |
return It(fns).reduce(lambda it, fn: It(filter(fn, it)), self) | |
def apply(self, *fns): | |
return It(fns).reduce(lambda it, fn: fn(it), self) | |
def apply_it(self, *fns): | |
return It(fns).reduce(lambda it, fn: It(fn(it)), self) | |
def chain(self, *iterables): | |
return It(itertools.chain(self, *iterables)) | |
def chain_after(self, *iterables): | |
return It(itertools.chain(*iterables, self)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment