Last active
December 21, 2018 17:03
-
-
Save JasonRammoray/a72766c74df6894c71f059a87a02fe6e to your computer and use it in GitHub Desktop.
Async tasks checker
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
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