4 ms·
The proper implementation looks kinda bulky to me. Are you not allowed to use promises? Feels more like a naive solution for anyone who has few months of experi
by gloosx 1y ago
The proper implementation looks kinda bulky to me. Are you not allowed to use promises? Feels more like a naive solution for anyone who has few months of experience with javascript or is it cheating?
const PromiseQueue = {
queue: Promise.resolve(true),
sendOnce(request) {
return new Promise((resolve, reject) => {
this.queue = this.queue
.then(request)
.then(resolve)
.catch(reject)
})
}
}
- mohsen1 1y agoNeat! and minimum delay can be done with Promise.race
- mind-blight 1y agoI actually tried to use this pattern to make an audio controller interface much nicer. If you get a long enough queue, you'll start to run into errors (I'm forgetting the exact message, but it was similar to a maximum recursion depth)
- gloosx 1y agoThis most likely happened because you had a queue operation which started another queue operation so a recursion was created which consumed every bit of memory it had available.
- damidekronik 1y agoAnd then once The Anyone gets few more years of experience they revert back to the bulky one.
- gloosx 1y agoDunno, every queue in every major library/project I saw is implemented like this. This is quite readable if you're familiar with js promises.
- MrDarcy 1y agoI believe you that this works, but I can’t easily read or comprehend it without considerable effort, so I’d grade it below a solution I could.
- gloosx 1y agoIf this is given in Javascript, I'd rate the promise solution higher since a Javascript job involves a ton of promisified async code like this. If this is given in C or pseudo-code, then for sure a good ol stack+flag+loop is looking good enough.
- craftkiller 1y ago> without considerable effort Are you sure? I'm not a javascript programmer and it took less than 2 minutes to comprehend. If you think this takes considerable effort to comprehend then I don't think you actually tried.
- dbetteridge 1y agoReadability over brevity for maintainable code (I know an interview doesn't require this, but I look for it) While this works, it's not exactly intuitive.
- gloosx 1y agoIn context of JS this kind of promisified async code is intuitive and this pattern is quite common in various projects and libraries, but the solution in C-like pseudocode of course looks more readable for general programming public.
- no_wizard 1y agoI agree, this seems incredibly readable to me, though I work in TypeScript / JavaScript all day and know the language and its patterns very well.
- a-priori 1y agoYou'll need to flatten the promise periodically if you use this approach, otherwise your performance will degrade a bit each time you enqueue something.