Couldn’t you just do cmd.run || cmd.fire || cmd.execute || cmd.callback ? I’m not super familiar with js. Worked with it a bit, but still not great, so please correct me if I’m wrong.
Nowadays you could also use the null coalesce operator ?? which would be preferable to || since logical or can be confused by false. For example, if cmd.fire is false, the result of || would be cmd.callback, the result of ?? would be cmd.fire.
That’s true, but in this case where you are seemingly wanting to save a function reference to call later, || would probably be the preferred method, seeing as you would be more likely to find an actual function, rather than a Boolean value. Otherwise later on it might equate to calling false(). Just my thoughts. Again, I’m not super familiar with js. My day job is mobile apps in Flutter/Dart.
both || and ?? seem like a wrong answer to me - if you want the first callable thing, but a nonempty string is supplied, and you call that, you get a TypeError
imo, the best possible solution for this problem is [cmd.run, cmd.fire, cmd.execute, cmd.callback].find(x => typeof x === 'function') || null
or, to avoid edge cases like that, just use typescript. it's 2021, if it's a new project then there is no reason not to
166
u/Koala_King_ Apr 22 '21
Couldn’t you just do
cmd.run || cmd.fire || cmd.execute || cmd.callback? I’m not super familiar with js. Worked with it a bit, but still not great, so please correct me if I’m wrong.