Skip to content

Instantly share code, notes, and snippets.

@tweinfeld
Last active March 25, 2017 22:53
Show Gist options
  • Save tweinfeld/f2a25378beebe727bbb99967b09ccf8f to your computer and use it in GitHub Desktop.
Save tweinfeld/f2a25378beebe727bbb99967b09ccf8f to your computer and use it in GitHub Desktop.
Transforms Iterables
// Here's a generic transformer helper function
const transform = (function(EMPTY) {
const transform = function*(iterable, trasformers) {
for (let res of iterable) {
for (let i = 0; i < trasformers.length && res !== EMPTY; i++) {
res = trasformers[i](res);
};
if (res !== EMPTY) yield res;
}
};
transform.filter = (func) => (val) => (func(val) ? val : EMPTY);
transform.map = (func) => (val) => func(val);
return transform;
})(Symbol('Empty'));
// Heres a usage scenario of the "transform" function
const FILE_PREFIX = "file:///";
let uris = new Set([
'file:///foo.txt',
'http:///npmjs.com',
'file:///bar/baz.txt'
]);
let newUris = new Set(
transform(uris, [
transform.filter((uri) => uri.startsWith(FILE_PREFIX)),
transform.map((uri) => uri.substr(FILE_PREFIX.length))
])
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment