Skip to content

Instantly share code, notes, and snippets.

@tonkotsuboy
Created April 20, 2018 06:21
Show Gist options
  • Save tonkotsuboy/83eaa718388160e5903c9080e93a1131 to your computer and use it in GitHub Desktop.
Save tonkotsuboy/83eaa718388160e5903c9080e93a1131 to your computer and use it in GitHub Desktop.
引数の配列を無限にループするイテレータの生成
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