Created
January 3, 2019 10:14
-
-
Save rytmis/a61686941630c17d6832fbdc2e61f8ef to your computer and use it in GitHub Desktop.
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
const Promise = require('bluebird'); | |
const reduceAsync = async (projection, initialValue, items) => { | |
let value = initialValue; | |
for (const item of items) { | |
value = await projection(value, item); | |
} | |
return value; | |
} | |
const mapAsync = async (projection, items) => { | |
return await reduceAsync( | |
async (acc, item) => [...acc, await projection(item)], | |
[], | |
items | |
); | |
} | |
const filterAsync = async (predicate, items) => { | |
return await reduceAsync( | |
async (acc, item) => { | |
const match = await predicate(item); | |
return match ? [...acc, item] : acc; | |
}, | |
[], | |
items | |
); | |
} | |
const findAsync = async (predicate, items) => { | |
for (const item of items) { | |
const match = await predicate(item); | |
if (match) { | |
return item; | |
} | |
} | |
return undefined; | |
} | |
let counter = 0; | |
const slowCounter = async () => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
counter += 1; | |
resolve(counter); | |
}, 200); | |
}) | |
} | |
const slowPredicate = async (actualPredicate, item) => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
resolve(actualPredicate(item)); | |
}, 200); | |
}) | |
} | |
const run = async () => { | |
const mapped = await mapAsync(slowCounter, ["foo", "bar", "baz"]); | |
console.log("Mapped:", mapped); | |
const found = await findAsync(async () => await slowCounter() > 6, ["you", "can't", "find", "me!", "I'm", "hiding"]); | |
console.log("Found:", found); | |
const filtered = await filterAsync( | |
async (item) => await slowPredicate(i => i !== "arthur", item), | |
["zaphod", "ford", "arthur", "marvin", "trillian"]); | |
console.log("Filtered:", filtered); | |
} | |
run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment