Skip to content

Instantly share code, notes, and snippets.

@rytmis
Created January 3, 2019 10:14
Show Gist options
  • Save rytmis/a61686941630c17d6832fbdc2e61f8ef to your computer and use it in GitHub Desktop.
Save rytmis/a61686941630c17d6832fbdc2e61f8ef to your computer and use it in GitHub Desktop.
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