mk-pmb / es-fallback-first-defined-value

Suggesting a new fallback operator for ECMAScript, like || but stops at first defined (!== undefined) value.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Simple solution

Alexsey opened this issue · comments

Hi!

In ECMAScript 2015 there were added method .find for arrays. With a help of that and arrow function syntax solution to your problem become as easy as

[
  guessFromColor(bev), 
  queryHwdb(bev.idVendor, bev.idProduct), 
  cfg && cfg.defaultSugars
].find(v => v !== undefined)
commented

Thanks, you're right! I'll update the "Cleaner looking wrapper function" approach.

(Update: Renamed to "Array literal's .find:" in commit 0bd6b2f.)

commented

Now that I have a pseudo-transpiler, it verified my expectation that this solution keeps the same drawback:

W: Wasting randomness for approach which logs next:
Cleaner looking wrapper function: 0

It produces the correct result but it differs from my suggested ?| operator in that it must evaluate all functions before it can know which ones could have been skipped. That's because the array literal fully initializes before any selection function is called, thus it would have been the same if I had used arrow syntax instead of the isDefined function.