LoginSignup
5

More than 5 years have passed since last update.

HaskellのreplicateみたいなやつをJavaScriptで実装してみる

Last updated at Posted at 2014-11-02

Haskellの、

replicate 5 5
[5,5,5,5,5]

みたいなのをJavaScriptで書いてみました。
さすがにreplicate 5 5なのは実装出来なかったので、
第二引数は配列にしました。

function replicate(n, x) {
  if (n <= 1) {
    return x;
  } else {
    x.push(x[0]);
    return replicate(n - 1, x);
  }
};
console.log(replicate(5,[5]));

こんな感じ。

追記

頂いたコメントからの改修版です。コメントそのまんまです。

function replicate(n, x) {
    if (n == 0) return [];
    return [x].concat(replicate(n - 1, x));
}

console.log(replicate(5, 5));

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
5