mercredi 5 juillet 2017

Javascript ifElse expression

Does javascript, or any popular js library, have a conditional/selection expression or function which emits a value?

I've been using promises more in my code which forces a more functional programming style, which is obfuscated by the fact that the if-else-statement in javascript (by virtue of being a statement) emits no value.

promiseFunction.then(value => { if (value) { return 1 } else { return 2 } })

This would be more simply written (strict evaluation of arguments notwithstanding) if there were a function (let's call it ifElse) that conditionally returned its second or third argument based on the value of its first:

promiseFunction.then(value => ifElse(value, 1, 2))

I understand that there's already language support for the conditional operator ?: however, it gets difficult to understand when nested:

promiseFunction.then(value => typeof value === 'undefined' ? value ? 'a' : 'b' : 'c')

The only thing I was able to find so far is this feature request in lodash which appears stalled.

Aucun commentaire:

Enregistrer un commentaire