Defining a range inside a switch in Coffeescript

I am using Handlebar in jQuery Rails 3.2 mobile app.

I am trying to write a case switch statement inside a Coffeescript method like

Handlebars.registerHelper 'status', (blog) ->
  switch(parseInt(blog.status))
    when [0..20]
      status = "active"
    when [20..40]
      status = "Moderately Active"
    when [40..60]
      status = "Very Active"
    when [60..100]
      status = "Hyper Active"
  return status

I do not get any result. How to use range when. Please suggest

+5
source share
2 answers

Yours switchwill not work like Cygal in the comments (for example, see number 1383 ). A switchis just an illustrious construction if(a == b), and you should be able to say things like:

a = [1,2,3]
switch a
...

, switch . CoffeeScript , () ( [a..b]) .

if:

Handlebars.registerHelper 'status', (blog) ->
  status = parseInt(blog.status, 10)
  if 0 <= status <= 20
    'Active'
  else if 20 < status <= 40
    'Moderately Active'
  else if 40 < status <= 60
    'Very Active'
  else if 60 < status <= 100
    'Hyper Active'
  else
    # You need to figure out what to say here

return :

Handlebars.registerHelper 'status', (blog) ->
  status = parseInt(blog.status, 10)
  return 'Something...'      if status <=   0
  return 'Active'            if status <=  20
  return 'Moderately Active' if status <=  40
  return 'Very Active'       if status <=  60
  return 'Hyper Active'      if status <= 100
  return 'Something else'    # This return isn't necessary but I like the symmetry

, , :

  • status < 0.
  • status > 100.
  • status - NaN. " 100", NaN => n NaN <= n n.

, , . , (, comp.risks), , .

radix parseInt, , . , radix , , , 10 parseInt.

+16

mu - , switch:

Handlebars.registerHelper 'status', (blog) ->
  status = parseInt(blog.status, 10)
  switch
    when status <= 0   then 'Something...'      
    when status <= 20  then 'Active'
    when status <= 40  then 'Moderately Active'
    when status <= 60  then 'Very Active'
    when status <= 100 then 'Hyper Active'
    else 'Something else'

switch (true) JavaScript ( CS switch (false) ... ).


, switch over , , CS JS ( - for i in [1..something]), , switch, :

// Generated JS for question CS code:
switch (parseInt(blog.status)) {
  case [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]:
    status = "active";
    break;
  case [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]:
    status = "Moderately Active";
    break;
  case [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]:
    status = "Very Active";
    break;
  case (function() {
      _results = [];
      for (_i = 60; _i <= 100; _i++){ _results.push(_i); }
      return _results;
    }).apply(this):
    status = "Hyper Active";
}

switch case, ===, , ( , , switch ed case ed).

+8

All Articles