LoginSignup
5
5

More than 5 years have passed since last update.

JavaScriptでPythonのrange関数のようにリスト作成

Posted at

Pythonのrange関数のように開始値と終わり値を指定してリストを作成する関数を毎回書きたくないのでモジュール化。

Pythonのrange関数

range([start, ]stop[, step])

>>> range(3,10)
[3, 4, 5, 6, 7, 8, 9]
>>> range(3,10,2)
[3, 5, 7, 9]

これをJavaScriptでもやりたい

JavaScriptでほぼ等価の関数

var jsrange = function (start, end, step) {
  var array = new Array();
  var step = step === undefined ? 1 : step;
  var counter = start;
  var index = 0;

  while (counter < end) {
    array.push(counter);
    counter += step;
  }

  return array;

}

module.exports = jsrange;

インストール

% npm install jsranger

使用例

var jsranger = require('jsranger');

var L = jsranger(2, 20);
console.log(L);
  // should display the following
  // [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 ]

var l = jsranger(2, 20, 2);
console.log(l);
  // should display the following
  // [ 2, 4, 6, 8, 10, 12, 14, 16, 18 ]

課題

数字以外の者が引数に来た時のエラーなど、引数のチェックを全くしてない

5
5
0

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
  3. You can use dark theme
What you can do with signing up
5
5