250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 중첩 점
- 자바스크립트
- 과제 진행하기
- jest
- 테스트 Date
- 귤 고르기
- 호텔 대실
- 최솟갑 구하기
- 날짜 테스트
- Hermes Engine
- 테이블 해시 함수
- Jest uuid syntax
- 프로그래머스
- 통신망분석
- Leetcode #javascript #알고리즘 #Algorithms #js
- 구름톤 챌린지
- nextjs-performance
- Google 애널리틱스
- 구름톤챌린지
- JavaScript
- nextjs
- 리액트네이티브 엔진
- mock date
- mutationobserver
- 리액트네이티브
- create-next-app
- 구름톤
- 헤르메스 엔진
- ResizeObserver
- 연결 요소 제거하기
Archives
- Today
- Total
나만보는개발공부블로그
Iterable & Iterator 본문
- ECMAScript2015(ES6)에 추가된 Protocol(규약)
Iterable protocol
반복 가능한 객체를 Iterable Obeject라 부르고 줄여서 iterable이라고 한다. 그리고 이러한 객체를 iterable protocol을 만족한다고 말한다.
Iterable을 만족하기위해서는 object에 @@iterator 메소드를 구현해야 한다. 즉 Symbol.iterator key 속성을 가져야 한다.
const CustomIteratorObj = {
[Symbol.iterator]: function* () {
for (let i = 1; i<10; ++i) yield i;
}
};
for(let s of CustomIteratorObj){
console.log(s);
}
위의 예제는 iteratble을 임의로 만들어내는 소스이다.
- String, Array, TypedArray, Map, Set이 속한다.
- for..of 구조 , 전개 문법, 구조 분해 할당 등에 사용될 수 있다.
- for...of
const array1 = ['a', 'b', 'c'];
for (const element of array1) {
console.log(element);
}
- Spread syntax(전개 문법)
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
console.log(sum.apply(null, numbers));
// expected output: 6
- Destructuring assigment(구조 분해 할당)
let a, b, rest;
[a, b] = [10, 20];
console.log(a);
// expected output: 10
console.log(b);
// expected output: 20
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
// expected output: Array [30,40,50]
Iterator protocol
value들의 sequence를 만드는 표준 방법을 정의한다. Iterator은 Iterable 객체에서 반복을 실행하는 반복기를 말한다.
아래 규칙이 있다면 Iterator라고 할 수 있다.
1. 객체 내의 next 메서드가 존재한다.
2. next 메서드는 Iterator 결과 객체를 반환한다.
3. Iterator 결과 객체에는 done: boolean 과 value: any 속성을 가진다.
4. 이전 next 메서드 호출의 결과로 done이 true를 반환하면 이후 호출에 대한 값도 true여야 한다.
const CustomIteratorObj = {
[Symbol.iterator]: function () {
let i = 1;
return {
next : function () {
if( i < 10) return {value: i++, done: false}
else return {done: true}
}
}
}
};
const it = CustomIteratorObj[Symbol.iterator]();
for (let i = 0; i < 10; ++i){
console.log(it.next())
}
'Javascript&Typescript' 카테고리의 다른 글
Shallow Copy & deep Copy (0) | 2021.03.23 |
---|---|
Hoisting (0) | 2021.03.04 |
FP & OOP (0) | 2021.02.22 |
classical & prototypal inheritance in javascript (0) | 2021.02.22 |
Declarative and Imperative programming (0) | 2021.02.21 |