2009/08/10

[JavaScript]srfiのiota

今日は少し寝不足で仕事中に激しい睡魔に襲われたので気分転換に書いた。

download

 

Arrayに非破壊的なmap追加してiotaっぽいの書いてfizzbuzzってみた。

Array.prototype.map = function (f)
{
  var ret = [];
  for (var i = 0; i < this.length; i++)
  {
    ret[i] = f(this[i]);
  }
  return ret;
};

function iota(cnt, init, inc)
{
  var ret = [];
  init = init || 0;
  inc = inc || 1;

  for (var i = 0, j = init; j < cnt; i++, (j = j + inc))
  {
    ret[i] = j;
  }
  return ret;
}

iota(100, 1).map(function (n){
                   var ret = n;
                   var modulo = function (divider)
                   {
                     return n % divider;
                   };

                   if (modulo(3) == 0)
                   {
                     ret = "fizz";
                   }
                   if (modulo(5) == 0)
                   {
                     ret = "buzz";
                   }
                   if (modulo(15) == 0)
                   {
                     ret = "fizzbuzz";
                   }

                   return ret;
                 });

0 件のコメント:

コメントを投稿