Skip to content

Instantly share code, notes, and snippets.

@JasonRammoray
Last active December 21, 2018 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JasonRammoray/a72766c74df6894c71f059a87a02fe6e to your computer and use it in GitHub Desktop.
Save JasonRammoray/a72766c74df6894c71f059a87a02fe6e to your computer and use it in GitHub Desktop.
Async tasks checker
class Foo {
constructor(time, answer) {
this._time = time;
this._answer = answer;
}
get time() {
return this._time;
}
is() {
return new Promise(res => setTimeout(() => res(this._answer), this._time));
}
}
async function find(items) {
let counter = items.length;
if (!counter) return null;
const result = new Promise(res => {
items.forEach(
item => {
item.is().then(isCompleted => {
if(isCompleted) return res(item);
if (--counter === 0) res(null);
})
}
);
});
return await result;
}
async function filter(items) {
const newItems = [];
let counter = items.length;
if (!counter) return newItems;
const result = new Promise(res => {
items.forEach(
item => {
item.is().then(isCompleted => {
if(isCompleted) newItems.push(item);
if (--counter === 0) res(newItems);
})
}
);
});
return await result;
}
// Tests
{
(async function() {
const foos = [new Foo(1000, true), new Foo(123, false), new Foo(125, true), new Foo(2349, false)];
const value = await find(foos);
console.assert(value.time === 125, 'Find -> positive case failed');
}());
}
{
(async function() {
const foos = [new Foo(1000, false), new Foo(123, false), new Foo(125, false), new Foo(2349, false)];
const value = await find(foos);
console.assert(value === null, 'Find -> edge case failed');
}());
}
{
(async function() {
const foos = [new Foo(1000, true), new Foo(123, false), new Foo(125, true), new Foo(2349, false)];
const values = await filter(foos);
const expected = [foos[2], foos[0]];
expected.forEach((item, index) => console.assert(item === values[index], 'Filter -> positive case failed'));
}());
}
{
(async function() {
const foos = [new Foo(1000, false), new Foo(123, false), new Foo(125, false), new Foo(2349, false)];
console.time('perf');
const values = await filter(foos);
console.timeEnd('perf');
console.assert(values.length === 0, 'Filter -> edge case failed');
}());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment