Sunday 21 November 2021

Infinite Sequence and More

It's good that I still find interest in bizarre programming topics :-) I recently came across an article about recursive iterators in javascript. What mainly called my attention was the recursive way to create and endless iterator. The "classical", iterative way is something along these lines:


function* infiniteIterable(iter){
    while (true){
        yield* iter;
    }
} 

The recursive way (I managed to write it myself without looking it on the article, to make sure I understood it) is this:


function* infiniteIterableViaRecursion(iter){
    yield* iter;
    yield* infiniteIterableViaRecursion(iter);
} 

Somehow I also came across this other post with an odd title Eliminate try..catch when using async/await by chaining .catch() clauses. What!? Avoiding the "Promise Hell" of a mass of chained then-catch calls and writing it as sequential code is why we all love async-await, so this seemed senseless. Well, looking into the article he refers to a case for which it makes good sense, when the async call returns a value and even in case of an exception we still want to return a (sort of default) value. So rather than this:


let value;
try {
  value = await db.get('nonexistent'); // throws NotFoundError
} catch {
  value = null;
}

We write this, that is quite more concise:


const value = await db.get('nonexistent').catch(() => null);

No comments:

Post a Comment