Print templates with ternary in coffeescript

0

How can I print ternary operators together with string templates using coffescript?

If I execute the code as:

peopleWithAgeDrink = (old)->
  "drink "+"#{'old<14?'toddy':old<18?'coke':old<21?'beer':'whisky''}"

I get the desired result, but

peopleWithAgeDrink = (old)->
  "drink #{'old<14?'toddy':old<18?'coke':old<21?'beer':'whisky''}"

gives erroneous results

    
asked by Ruslan López 04.05.2016 в 02:46
source

1 answer

0

If you want to use the ternary (or conditional) operator:

peopleWithAgeDrink = (old)->
  "drink #{if old < 14 then 'toddy' else if old < 18 then 'coke' else if old < 21 then 'beer' else 'whisky'}"

The conditional operator in CoffeeScript follows the form of

if <condición> then <valor1> else <valor2>

But I would not recommend writing multiple conditions in this way.

You are also using the ' symbol (grave accent or backtick ) in the template . This symbol is not for strings , what it does is indicate to CoffeeScript that what is enclosed in ' ' should interpret it as regular JavaScript and not translate it. This has valid uses but I recommend that you do not use it until you are quite familiar with CoffeeScript.

Another more idiomatic way to write this in CoffeeScript would be:

peopleWithAgeDrink = (old) ->
    "drink #{
        switch
          when old < 14 then 'toddy'
          when old < 18 then 'coke'
          when old < 21 then 'beer'
          else 'whisky'
    }"

Now if you already understand the problems of mixing JavaScript with Coffeescript and still want to do it that way:

Not recommended

peopleWithAgeDrink = (old)->
  "drink #{'(old<14?'toddy':old<18?'coke':old<21?'beer':'whisky')'}"

What the code lacked was parentheses to evaluate the expression in the correct order.

    
answered by 04.05.2016 / 04:54
source