주사위 열번 굴리는 제네레이터
function* diceTenTimes () {
let count = 0;
const maxCount = 10;
while (count++ < maxCount) {
yield Math.ceil(Math.random() * 6);
}
}
// 이터러블
console.log(
[...diceTenTimes()]
);
// 이터레이터 - 객체로 반환 뒤 사용
// ⚠️ 다시 순회시 재생성 필요
let diceGenObj = diceTenTimes();
for (let i = 0; i < 12; i++) {
console.log(diceGenObj.next());
}
피보나치 제네레이터
function* fibonacci (maxCount) {
let count = 0;
let [x, y] = [0, 1];
while (count++ < maxCount) {
[x, y] = [y, x + y];
yield y;
}
}
console.log(
[...fibonacci(10)]
);
let fiboGenObj = fibonacci(5);
for (let i = 0; i < 7; i++) {
console.log(
fiboGenObj.next()
);
}
순번 제네레이터
function* workersGen (people) {
let idx = 0;
while (idx < people.length) {
yield people[idx++];
}
}
const team1 = [
'철수', '영희', '돌준', '미나', '준희'
];
console.log(
[...workersGen(team1)]
);
// 이터레이터로 사용
// 인원 순번 넘기기
function switchWorker(iter) {
const next = iter.next();
console.log(
next.done
? '-- 인원 없음 -- '
: `${next.value} 차례입니다.`
);
}
workersIter1 = workersGen(team1);
switchWorker(workersIter1);
switchWorker(workersIter1);
switchWorker(workersIter1);
switchWorker(workersIter1);
switchWorker(workersIter1);
switchWorker(workersIter1);
switchWorker(workersIter1);
댓글 영역