Last active
March 25, 2017 22:53
-
-
Save tweinfeld/f2a25378beebe727bbb99967b09ccf8f to your computer and use it in GitHub Desktop.
Transforms Iterables
This file contains hidden or 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
// 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