あいつの日誌β

働きながら旅しています。

ES6 での range 関数を書いてみた

あらすじ

Ruby でいう to_a のアレを JavaScript で書いてみた

function range(from, to) {
  return [...Array(to - from + 1).keys()].map(x => x + from)
}

console.log(range(0, 10))
console.log(range(3, 10))

出力結果

[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
[ 3, 4, 5, 6, 7, 8, 9, 10 ]

なんだけど

range 関数の from, to のインターフェースなんですがどっちが一般的なんでしょう?

console.log(range(1, 10))
console.log(Immutable.Range(1, 10).toArray())

出力結果

[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

今度誰かと会った時の話題にしよう