Created
April 20, 2018 06:21
-
-
Save tonkotsuboy/83eaa718388160e5903c9080e93a1131 to your computer and use it in GitHub Desktop.
引数の配列を無限にループするイテレータの生成
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class IteratorUtil { | |
/** | |
* 引数の配列を無限にループするイテレータの生成 | |
* @param {Array<T>} array | |
* @param {boolean} skipNullValue: nullの値をスキップするかどうか | |
* @returns {Iterator<T>} | |
* | |
* 使い方 | |
* | |
* const myArray = [1, 2, 3]; | |
* const iterator = IteratorUtil.createInfiniteArrayIterator(); | |
* | |
* console.log(iterator.next()); // 1 | |
* console.log(iterator.next()); // 2 | |
* console.log(iterator.next()); // 3 | |
* console.log(iterator.next()); // 1 ☆ | |
* console.log(iterator.next()); // 2 ☆ | |
* | |
*/ | |
static *createInfiniteArrayIterator<T>( | |
array: Array<T>, | |
skipNullValue: boolean = true | |
): Iterator<T> { | |
let index = 0; | |
while (true) { | |
// skipNullValueがtrueならば、値が空でないものだけを返す | |
if (skipNullValue === true && array[index] != null) { | |
yield array[index]; | |
} | |
index += 1; | |
if (index >= array.length) { | |
index = 0; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment