Skip to content

Instantly share code, notes, and snippets.

@shoveller
Last active March 30, 2018 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shoveller/f307a975d784486d9dda5fe994741eda to your computer and use it in GitHub Desktop.
Save shoveller/f307a975d784486d9dda5fe994741eda to your computer and use it in GitHub Desktop.
커스텀 이터레이터로 구현한 레인지 함수
function range(start, end, step = 1) {
const iterable = {
[Symbol.iterator]() {
let value = start;
const iterator = {
next() {
value = value + step;
let done = value === end + step;
if (done) {
value = null;
}
const iteratorResult = { done, value };
return iteratorResult;
}
};
return iterator;
}
};
return iterable;
}
for (const val of range(0, 2)) {
console.log(val); // 0 1 2
}
@shoveller
Copy link
Author

shoveller commented Mar 30, 2018

이 커스텀 이터레이터는 제너레이터 함수와 yield 키워드를 사용하면 보다 간략하게 구현할 수 있다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment