Skip to content

Instantly share code, notes, and snippets.

@sashee
Created January 10, 2020 08:47
Show Gist options
  • Save sashee/1bf5a80eb2ee00158306be47723dc9ff to your computer and use it in GitHub Desktop.
Save sashee/1bf5a80eb2ee00158306be47723dc9ff 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 some");
const arr = [1, 2, 3];
const res = arr.some((i) => {
console.log(`Checking ${i}`);
return i % 2 === 0;
});
// Checking 1
// Checking 2
console.log(res);
// true
}
{
console.log("\nasync some");
const arr = [1, 2, 3];
const asyncSome = async (arr, predicate) => {
for (let e of arr) {
if (await predicate(e)) return true;
}
return false;
};
const res = await asyncSome(arr, async (i) => {
console.log(`Checking ${i}`);
await sleep(10);
return i % 2 === 0;
});
// Checking 1
// Checking 2
console.log(res);
// true
}
{
console.log("\nsync every");
const arr = [1, 2, 3];
const res = arr.every((i) => {
console.log(`Checking ${i}`);
return i < 2;
});
// Checking 1
// Checking 2
console.log(res);
// false
}
{
console.log("\nasync every");
const arr = [1, 2, 3];
const asyncEvery = async (arr, predicate) => {
for (let e of arr) {
if (!await predicate(e)) return false;
}
return true;
};
const res = await asyncEvery(arr, async (i) => {
console.log(`Checking ${i}`);
await sleep(10);
return i < 2;
});
// Checking 1
// Checking 2
console.log(res);
// false
}
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment