4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JavaScriptでrange関数を作る

Last updated at Posted at 2018-06-06

備忘録。
もっと速いのがあればご教示ください。

その1 オーソドックス

const range = size => {
  const range = Array(size);
  for (let i = 0; i < size; i++) {
    range[i] = i;
  }
  return range;
};

start, stepを実装すると

const range = (start, end, step) => {
  if (typeof end === 'undefined') {
    end = start || 0;
    start = 0;
  }
  if (!step) {
    step = end > start ? 1 : -1;
  }
  const length = Math.max(Math.ceil((end - start)/step), 0);
  const range = Array(length);
  for (let i = 0; i < length; i++, start += step) {
    range[i] = start;
  }
  return range;
};
  • underscore.jsを模倣した
  • 結局これが一番早い

その2 一行

const range = size => [...Array(size).keys()];

start, stepを実装すると

const range = (start, end, step) => [...Array(Math.max(Math.ceil((end - start)/step), 0)).keys()].map(n => n*step + start);
  • 引数を省略できない(省略したけりゃその1を使う)
  • 速そうで遅い

その3 うーん

const range = size => Array.from({length: size}, (x, i) => i);

うーーん

4
2
1

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
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?