Skip to content

Instantly share code, notes, and snippets.

@sashee
Last active January 13, 2020 09:15
Show Gist options
  • Save sashee/cf366adf82d3392010ca610ce6094fb8 to your computer and use it in GitHub Desktop.
Save sashee/cf366adf82d3392010ca610ce6094fb8 to your computer and use it in GitHub Desktop.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<script>
console.log = (msg) => document.body.innerText += `${msg}\n`;
// utility function for sleeping
const sleep = (n) => new Promise((res) => setTimeout(res, n));
(async () => {
{
console.log("\nsync filter");
const arr = [1, 2, 3, 4, 5];
const syncRes = arr.filter((i) => {
return i % 2 === 0;
});
console.log(syncRes);
// 2,4
}
{
console.log("\nasync filter");
const arr = [1, 2, 3, 4, 5];
const asyncFilter = async (arr, predicate) => {
const results = await Promise.all(arr.map(predicate));
return arr.filter((_v, index) => results[index]);
}
const asyncRes = await asyncFilter(arr, async (i) => {
console.log(`S ${i}`);
await sleep(10);
console.log(`F ${i}`);
return i % 2 === 0;
});
console.log(asyncRes);
// 2,4
}
{
console.log("\nasync filter with reduce");
const arr = [1, 2, 3, 4, 5];
const asyncFilter = async (arr, predicate) =>
arr.reduce(async (memo, e) => await predicate(e) ? [...await memo, e] : memo, []);
const asyncRes = await asyncFilter(arr, async (i) => {
console.log(`S ${i}`);
await sleep(10);
console.log(`F ${i}`);
return i % 2 === 0;
});
console.log(asyncRes);
// 2,4
}
{
console.log("\nasync filter with reduce, serially");
const arr = [1, 2, 3, 4, 5];
const asyncFilter = async (arr, predicate) =>
arr.reduce(async (memo, e) => [...await memo, ...await predicate(e) ? [e] : []], []);
const asyncRes = await asyncFilter(arr, async (i) => {
console.log(`S ${i}`);
await sleep(10);
console.log(`F ${i}`);
return i % 2 === 0;
});
console.log(asyncRes);
// 2,4
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment