JavaScript Range

JavaScript Range
0

#1

Coming from Ruby it’s always bothered me that Javascript doesn’t have a true range function. This can be offset with the right library but of late I’ve just done [...Array(limit).keys()] This works fine when I want a range from zero to some limit. But what if I want to start at something other than 0?

Here is a classic FizzBuzz.

function fizzBuzz(num){
  [...Array(num).keys()].map((x)=>{
    x++;
    let ans = (x%15 === 0 ) ? 'fizzBuzz':
                            (x%5 === 0 ) ? 'buzz':
                                  (x%3 === 0) ? 'fizz': x;
    return console.log(ans);
  });
}

fizzBuzz(30);

Line 3 doesn’t feel very clean. Is there a better way?


#2
function fizzBuzz(num){
  [...Array(num).keys()].map((x)=>{
    return console.log(++x % 15 === 0
      ? 'fizzBuzz':
        x%5 === 0  ? 'buzz':
          x%3 === 0 ? 'fizz': x);
  });
}

Notice the ++x on line 3.


#3

My question when I see such a solution as above, is why create arrays, when you do not have to.

function fizzBuzz(num) {
  for (var i=1;i<=num;i++) {
    var str='';
    if (i%3===0) str+='fizz';
    if (i%5===0) str+='buzz';
    console.log(str==='' ? i : str);
  }
}