Conditional operator in Coffeescript

CoffeescriptConditional Operator

Coffeescript Problem Overview


I really like this:

var value = maxValue > minValue ? minValue : maxValue;

Is there something equally concise in Coffescript?

Coffeescript Solutions


Solution 1 - Coffeescript

value = if maxValue > minValue then minValue else maxValue

Solution 2 - Coffeescript

There is a more concise option in both javascript and coffeescript :)

value = Math.min(minValue, maxValue)

Solution 3 - Coffeescript

As Răzvan Panda points out, my comment may actually one of the better answers:

value = `maxValue > minValue ? minValue : maxValue`

Solution 4 - Coffeescript

This is a case where it feels like CoffeeScript has competing philosophies:

  1. Be concise
  2. Don't be redundant

Since all operations return a result, the if/then/else way of doing things gives you what you need. Adding the ?/: operator is redundant.

This is where I wish they'd give us the ?/: ternary operator even though it is redundant... it simply reads better than the if/then/else variant.

Just my 2c.

Solution 5 - Coffeescript

You can write it like this:

value = if maxValue > minValue then minValue else maxValue

It will compile like your code.

Solution 6 - Coffeescript

Below is the fact:

In the documentation, there's a section titled "Conditionals, Ternaries, and Conditional Assignment". This leads one to believe that coffeescript supports

condition ? when-true : when-false 

but in fact it does not.

Below is the information about the patch which will solve this issue

Here's the patch (and it's pushed to coffeescript.org):

http://github.com/jashkenas/coffee-script/commit/ec2d358ae3c82e9888c60695d7cce05edde0c55a

Examples:

mood = greatlyImproved if singing

if happy and knowsIt
  clapsHands()
  chaChaCha()
else
  showIt()

date = if friday then sue else jill

options or= defaults

Solution 7 - Coffeescript

value = maxValue > minValue && minValue || maxValue

This is actually not correct, check the comments.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBlubView Question on Stackoverflow
Solution 1 - CoffeescriptTim CooperView Answer on Stackoverflow
Solution 2 - CoffeescriptRicardo TomasiView Answer on Stackoverflow
Solution 3 - CoffeescriptPeter KrnjevicView Answer on Stackoverflow
Solution 4 - CoffeescriptBrian GenisioView Answer on Stackoverflow
Solution 5 - Coffeescriptv42View Answer on Stackoverflow
Solution 6 - CoffeescriptSiva CharanView Answer on Stackoverflow
Solution 7 - CoffeescriptSergey SemenovView Answer on Stackoverflow