1
0

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 3 years have passed since last update.

【javascript】一行で書かないrange関数

Last updated at Posted at 2020-10-31

ワンライナー以外の記述をしたかった。

###コード

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で返す
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?