이 예제는 두 이터레이터가 서로 독립적이며 같은 배열에서 따로따로 움직일 수 있음을 보여줍
니다.
12.1
이터레이션 프로토콜
이터레이터는 그 자체로 크게 쓸모가 있다기보다는, 더 쓸모 있는 동작이 가능해지도록 한다는
데 의미가 있습니다.
이터레이터 프로토콜
은 모든 객체를 이터러블
iterable
객체로 바꿀 수 있습
니다. 메시지에 타임스탬프를 붙이는 로그 클래스가 필요하다고 생각해 봅시다. 내적으로 타임
스탬프가 붙은 메시지는 배열에 저장합니다.
class
Log
{
constructor
() {
this
.
messages
= [];
}
add
(
message
) {
this
.
messages
.
push
({
message
,
timestamp
:
Date
.
now
() });
}
}
지금까지는 좋습니다만, 로그를 기록한 항목을 순회
iterate
하고 싶다면 어떻게 해야 할까요? 물
론
log
.
messages
에 접근할 수는 있지만,
log
를 배열을 조작하듯 할 수 있다면 더 좋을 겁니다.
이터레이션 프로토콜을 사용하면 가능합니다. 이터레이션 프로토콜은 클래스에 심볼 메서드
Symbol
.
iterator
가 있고 이 메서드가 이터레이터처럼 동작하는 객체, 즉
value
와
done
프로
퍼티가 있는 객체를 반환하는
next
메서드를 가진 객체를 반환한다면 그
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.
O’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
I wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
I’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
I'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.