ワンライナー以外の記述をしたかった。
###コード
const range = (from, to, step) => {
if (Number.isFinite(from) === false) from = 0;
if (Number.isFinite(to) === false) to = 0;
if (Number.isFinite(step) === false || step < 1) step = 1;
if (from === to) return [to];
const result = new Array();
if (from < to) {
for (; from <= to; from += step) result.push(from);
} else {
for (; from >= to; from -= step) result.push(from);
}
return result;
};
console.log( range() ); //[0]
console.log( range(5, 5) ); //[5]
console.log( range(-5) ); //[-5, -4, -3, -2, -1, 0]
console.log( range(5) ); //[5, 4, 3, 2, 1, 0]
console.log( range(-5, 5) ); //[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]
console.log( range(5, -5) ); //[5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5]
console.log( range(-5, 5, 2) ); //[-5, -3, -1, 1, 3, 5]
console.log( range(5, -5, 2) ); //[5, 3, 1, -1, -3, -5]
###コード(修正)
引数が空の時と、1個の時の結果が不満だったので。
const range = function (from, to, step) {
const length = arguments.length;
if (length===0) return new Array();
if (Number.isFinite(from) === false) from = 0;
if (length===1 && from > 0) to = from, from = 0;
if (Number.isFinite(to) === false) to = 0;
if (from === to) return Array.of(to);
if (Number.isFinite(step) === false || step < 1) step = 1;
const result = new Array();
if (from < to) {
for (; from <= to; from += step) result.push(from);
} else {
for (; from >= to; from -= step) result.push(from);
}
return result;
};
console.log( range() ); //(新)[](旧)[0]
console.log( range(-5) ); //[-5, -4, -3, -2, -1, 0]
console.log( range(5) ); //(新)[0, 1, 2, 3, 4, 5](旧)[5, 4, 3, 2, 1, 0]
##変更点
- アロー関数は
arguments
が使えないのでfunction
に変更 - 引数が空の時、空の配列を返す
- 引数が1個且つ0より大きい時、
from->0
ではなく0->from
で返す