SlideShare a Scribd company logo
3
generator
기존의 루프는 추상화가 불가함.
Abstract Loop
기존에는 루프 전체의 실행여부를 결정만 추상화할 수 있음.
루프의 추상화?
const elLoop = (el, f)=>{
const stack = [];
do{
f(el);
if(el.firstElementChild) stack.push(el.firstElementChild);
if(el.nextElementSibling) stack.push(el.nextElementSibling);
}while(el = stack.pop());
};
const elLoopWithFilter = (el, run, filter)=>{
const stack = [];
do{
if(filter(el)) run(el);
if(el.firstElementChild) stack.push(el.firstElementChild);
if(el.nextElementSibling) stack.push(el.nextElementSibling);
}while(el = stack.pop());
};
const elLoopWithFilter = (el, run, filter)=> elLoop(el, el=>filter(el) && run(el));
[1,2,3].forEach(v=>console.log(v));
Generator는 루프구조의 추상화를 가능하게 함
Abstract Loop
const elLoop = function*(el) {
const stack = [];
do{
yield(el);
if(el.firstElementChild) stack.push(el.firstElementChild);
if(el.nextElementSibling) stack.push(el.nextElementSibling);
}while(el = stack.pop());
};
for(const el of elLoop(document.getElementById('a'))){
if(el.tagName == 'article' && el.innerHTML.startWiths('projectA')) return el;
}
composite, visitor, iterator, decorator, cor 등의 복합적인 루프를 모두 추상화하여 for of로 노출
Abstract Loop
const is = (v, cls)=>{
if(!(v instanceof cls) throw 'invalid type';
};
const Composite = class{
constructor(title){
this.title = title;
this.children = new Set();
}
add(child, type = is(child, Composite)){
this.children.add(child);
}
*operation(){
yield this.title;
for(const c of this.children) yield* c.operation();
}
[Symbol.iterator](){
return this.operation();
}
}
let P = new Composite('parent');
P.add(new Composite('child1'));
P.add(new Composite('child2'));
for(const title of P) console.log(title);
루프를 지연하여 필요한 만큼만 루프를 돌면서 문제를 해결하고 루프가 시작되기 전에는 부하를 걸지 않음
Lazy Loop(Loop to Value)
const each = function*(arr){
console.log('each start');
for(const v of arr.slice(0)){
console.log('each:', v);
yield v;
}
};
const filter = function*(e, f){
console.log('filter start');
for(const v of e){
if(f(v)){
console.log('filter:', i);
yield v;
}
}
}
const map = function*(e, f){
console.log('map start');
for(const v of e){
console.log('map:', v);
yield f(v);
}
}
for(const v of
each([1,2,3,4])
) console.log(v); for(const v of
filter(each([1,2,3,4]), v=>(v%2 == 0))
) console.log(v);
for(const v of
map(
filter(each([1,2,3,4]), v=>(v%2 == 0)),
v=>v*2)
) console.log(v);
lazy chaining
const lazy = (_=>{
const gene = function*(iter){for(const v of iter) yield v; };
const filter = function*(g, f){for(const v of g) if(f(v)) yield v;};
const map = function*(g, f){for(const v of g) yield f(v);};
const Lazy = class{
constructor(iter){this.seed = gene(iter); }
[Symbol.iterator](){return this.seed; }
filter(f){
this.seed = filter(this.seed, f);
return this;
}
map(f){
this.seed = map(this.seed, f);
return this;
}
};
return v=>new Lazy(v);
})();
for(const v of lazy([1,2,3,4])) console.log(v);
for(const v of
lazy([1,2,3,4])
.filter(v=>v % 2 == 0)
) console.log(v);
for(const v of
lazy([1,2,3,4])
.filter(v=>v % 2 == 0)
.map(v=>v*2)
) console.log(v);

More Related Content

DOCX
Quinto Punto Parte B
DOCX
Primer Punto
KEY
Lock? We don't need no stinkin' locks!
PPTX
Reverse Engineering: C++ "for" operator
PPTX
What is recursion?
PDF
OOP in Rust
PPTX
PDF
Perl 5.16 new features
Quinto Punto Parte B
Primer Punto
Lock? We don't need no stinkin' locks!
Reverse Engineering: C++ "for" operator
What is recursion?
OOP in Rust
Perl 5.16 new features

What's hot (7)

PDF
Capture and replay hardware behaviour for regression testing and bug reporting
PDF
Javascript basics
PDF
東急Ruby会議向け「rubyの細かい話」
PDF
Clojurescript up and running
DOC
Tarea De Scilab By Sebastian Vasquez
PPTX
Teorical 1
PDF
Mr. Rochester
Capture and replay hardware behaviour for regression testing and bug reporting
Javascript basics
東急Ruby会議向け「rubyの細かい話」
Clojurescript up and running
Tarea De Scilab By Sebastian Vasquez
Teorical 1
Mr. Rochester
Ad

Viewers also liked (20)

PDF
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
PDF
[D2 오픈세미나]1.무한스크롤성능개선
PDF
데이터분석과통계2 - 최재걸님
PPTX
Papago/N2MT 개발이야기
PDF
텀 프로젝트에서 제품 프로젝트로 - 성준영님
PDF
[D2 오픈세미나]4.네이티브앱저장통신
PDF
[D2 오픈세미나]2.모바일웹디버깅
PDF
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 4. promise
PDF
[D2 오픈세미나]5.robolectric 안드로이드 테스팅
PDF
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions
PDF
[D2 오픈세미나]3.web view hybridapp
PDF
JavaScript 비동기 프로그래밍 집중 탐구 - 조유성님
PDF
[D2 COMMUNITY] Open Container Seoul Meetup - 마이크로 서비스 아키텍쳐와 Docker kubernetes
PDF
[D2 COMMUNITY] Open Container Seoul Meetup - Running a container platform in ...
PDF
[D2 COMMUNITY] Open Container Seoul Meetup - Docker security
PDF
blue-green deployment with docker containers
PDF
[D2 COMMUNITY] Open Container Seoul Meetup - Kubernetes를 이용한 서비스 구축과 openshift
PPTX
Container & kubernetes
PDF
Docker d2 박승환
PDF
[고려대 ALPS&ALKOR] 프로그래밍 경진대회 문제
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 1. primitive
[D2 오픈세미나]1.무한스크롤성능개선
데이터분석과통계2 - 최재걸님
Papago/N2MT 개발이야기
텀 프로젝트에서 제품 프로젝트로 - 성준영님
[D2 오픈세미나]4.네이티브앱저장통신
[D2 오픈세미나]2.모바일웹디버깅
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 4. promise
[D2 오픈세미나]5.robolectric 안드로이드 테스팅
[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 2. functions
[D2 오픈세미나]3.web view hybridapp
JavaScript 비동기 프로그래밍 집중 탐구 - 조유성님
[D2 COMMUNITY] Open Container Seoul Meetup - 마이크로 서비스 아키텍쳐와 Docker kubernetes
[D2 COMMUNITY] Open Container Seoul Meetup - Running a container platform in ...
[D2 COMMUNITY] Open Container Seoul Meetup - Docker security
blue-green deployment with docker containers
[D2 COMMUNITY] Open Container Seoul Meetup - Kubernetes를 이용한 서비스 구축과 openshift
Container & kubernetes
Docker d2 박승환
[고려대 ALPS&ALKOR] 프로그래밍 경진대회 문제
Ad

Similar to [D2 COMMUNITY] ECMAScript 2015 S67 seminar - 3. generator (6)

PDF
Javascript: The Important Bits
PDF
Understanding greenlet
PDF
Stack switching for fun and profit
KEY
Gevent what's the point
PDF
A Prelude of Purity: Scaling Back ZIO
PPTX
Data Structures and Agorithm: DS 06 Stack.pptx
Javascript: The Important Bits
Understanding greenlet
Stack switching for fun and profit
Gevent what's the point
A Prelude of Purity: Scaling Back ZIO
Data Structures and Agorithm: DS 06 Stack.pptx

More from NAVER D2 (20)

PDF
[211] 인공지능이 인공지능 챗봇을 만든다
PDF
[233] 대형 컨테이너 클러스터에서의 고가용성 Network Load Balancing: Maglev Hashing Scheduler i...
PDF
[215] Druid로 쉽고 빠르게 데이터 분석하기
PDF
[245]Papago Internals: 모델분석과 응용기술 개발
PDF
[236] 스트림 저장소 최적화 이야기: 아파치 드루이드로부터 얻은 교훈
PDF
[235]Wikipedia-scale Q&A
PDF
[244]로봇이 현실 세계에 대해 학습하도록 만들기
PDF
[243] Deep Learning to help student’s Deep Learning
PDF
[234]Fast & Accurate Data Annotation Pipeline for AI applications
PDF
Old version: [233]대형 컨테이너 클러스터에서의 고가용성 Network Load Balancing
PDF
[226]NAVER 광고 deep click prediction: 모델링부터 서빙까지
PDF
[225]NSML: 머신러닝 플랫폼 서비스하기 & 모델 튜닝 자동화하기
PDF
[224]네이버 검색과 개인화
PDF
[216]Search Reliability Engineering (부제: 지진에도 흔들리지 않는 네이버 검색시스템)
PDF
[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기
PDF
[213] Fashion Visual Search
PDF
[232] TensorRT를 활용한 딥러닝 Inference 최적화
PDF
[242]컴퓨터 비전을 이용한 실내 지도 자동 업데이트 방법: 딥러닝을 통한 POI 변화 탐지
PDF
[212]C3, 데이터 처리에서 서빙까지 가능한 하둡 클러스터
PDF
[223]기계독해 QA: 검색인가, NLP인가?
[211] 인공지능이 인공지능 챗봇을 만든다
[233] 대형 컨테이너 클러스터에서의 고가용성 Network Load Balancing: Maglev Hashing Scheduler i...
[215] Druid로 쉽고 빠르게 데이터 분석하기
[245]Papago Internals: 모델분석과 응용기술 개발
[236] 스트림 저장소 최적화 이야기: 아파치 드루이드로부터 얻은 교훈
[235]Wikipedia-scale Q&A
[244]로봇이 현실 세계에 대해 학습하도록 만들기
[243] Deep Learning to help student’s Deep Learning
[234]Fast & Accurate Data Annotation Pipeline for AI applications
Old version: [233]대형 컨테이너 클러스터에서의 고가용성 Network Load Balancing
[226]NAVER 광고 deep click prediction: 모델링부터 서빙까지
[225]NSML: 머신러닝 플랫폼 서비스하기 & 모델 튜닝 자동화하기
[224]네이버 검색과 개인화
[216]Search Reliability Engineering (부제: 지진에도 흔들리지 않는 네이버 검색시스템)
[214] Ai Serving Platform: 하루 수 억 건의 인퍼런스를 처리하기 위한 고군분투기
[213] Fashion Visual Search
[232] TensorRT를 활용한 딥러닝 Inference 최적화
[242]컴퓨터 비전을 이용한 실내 지도 자동 업데이트 방법: 딥러닝을 통한 POI 변화 탐지
[212]C3, 데이터 처리에서 서빙까지 가능한 하둡 클러스터
[223]기계독해 QA: 검색인가, NLP인가?

Recently uploaded (20)

PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPT
Mechanical Engineering MATERIALS Selection
PDF
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PPT
Project quality management in manufacturing
PPTX
additive manufacturing of ss316l using mig welding
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
Safety Seminar civil to be ensured for safe working.
PPTX
Sustainable Sites - Green Building Construction
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
Fundamentals of Mechanical Engineering.pptx
DOCX
573137875-Attendance-Management-System-original
PPT
introduction to datamining and warehousing
PPTX
UNIT 4 Total Quality Management .pptx
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
Construction Project Organization Group 2.pptx
PDF
Categorization of Factors Affecting Classification Algorithms Selection
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PPTX
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PPT
Total quality management ppt for engineering students
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Mechanical Engineering MATERIALS Selection
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
Project quality management in manufacturing
additive manufacturing of ss316l using mig welding
Internet of Things (IOT) - A guide to understanding
Safety Seminar civil to be ensured for safe working.
Sustainable Sites - Green Building Construction
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Fundamentals of Mechanical Engineering.pptx
573137875-Attendance-Management-System-original
introduction to datamining and warehousing
UNIT 4 Total Quality Management .pptx
Embodied AI: Ushering in the Next Era of Intelligent Systems
Construction Project Organization Group 2.pptx
Categorization of Factors Affecting Classification Algorithms Selection
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
Total quality management ppt for engineering students

[D2 COMMUNITY] ECMAScript 2015 S67 seminar - 3. generator

  • 2. 기존의 루프는 추상화가 불가함. Abstract Loop 기존에는 루프 전체의 실행여부를 결정만 추상화할 수 있음. 루프의 추상화? const elLoop = (el, f)=>{ const stack = []; do{ f(el); if(el.firstElementChild) stack.push(el.firstElementChild); if(el.nextElementSibling) stack.push(el.nextElementSibling); }while(el = stack.pop()); }; const elLoopWithFilter = (el, run, filter)=>{ const stack = []; do{ if(filter(el)) run(el); if(el.firstElementChild) stack.push(el.firstElementChild); if(el.nextElementSibling) stack.push(el.nextElementSibling); }while(el = stack.pop()); }; const elLoopWithFilter = (el, run, filter)=> elLoop(el, el=>filter(el) && run(el)); [1,2,3].forEach(v=>console.log(v));
  • 3. Generator는 루프구조의 추상화를 가능하게 함 Abstract Loop const elLoop = function*(el) { const stack = []; do{ yield(el); if(el.firstElementChild) stack.push(el.firstElementChild); if(el.nextElementSibling) stack.push(el.nextElementSibling); }while(el = stack.pop()); }; for(const el of elLoop(document.getElementById('a'))){ if(el.tagName == 'article' && el.innerHTML.startWiths('projectA')) return el; }
  • 4. composite, visitor, iterator, decorator, cor 등의 복합적인 루프를 모두 추상화하여 for of로 노출 Abstract Loop const is = (v, cls)=>{ if(!(v instanceof cls) throw 'invalid type'; }; const Composite = class{ constructor(title){ this.title = title; this.children = new Set(); } add(child, type = is(child, Composite)){ this.children.add(child); } *operation(){ yield this.title; for(const c of this.children) yield* c.operation(); } [Symbol.iterator](){ return this.operation(); } } let P = new Composite('parent'); P.add(new Composite('child1')); P.add(new Composite('child2')); for(const title of P) console.log(title);
  • 5. 루프를 지연하여 필요한 만큼만 루프를 돌면서 문제를 해결하고 루프가 시작되기 전에는 부하를 걸지 않음 Lazy Loop(Loop to Value) const each = function*(arr){ console.log('each start'); for(const v of arr.slice(0)){ console.log('each:', v); yield v; } }; const filter = function*(e, f){ console.log('filter start'); for(const v of e){ if(f(v)){ console.log('filter:', i); yield v; } } } const map = function*(e, f){ console.log('map start'); for(const v of e){ console.log('map:', v); yield f(v); } } for(const v of each([1,2,3,4]) ) console.log(v); for(const v of filter(each([1,2,3,4]), v=>(v%2 == 0)) ) console.log(v); for(const v of map( filter(each([1,2,3,4]), v=>(v%2 == 0)), v=>v*2) ) console.log(v);
  • 6. lazy chaining const lazy = (_=>{ const gene = function*(iter){for(const v of iter) yield v; }; const filter = function*(g, f){for(const v of g) if(f(v)) yield v;}; const map = function*(g, f){for(const v of g) yield f(v);}; const Lazy = class{ constructor(iter){this.seed = gene(iter); } [Symbol.iterator](){return this.seed; } filter(f){ this.seed = filter(this.seed, f); return this; } map(f){ this.seed = map(this.seed, f); return this; } }; return v=>new Lazy(v); })(); for(const v of lazy([1,2,3,4])) console.log(v); for(const v of lazy([1,2,3,4]) .filter(v=>v % 2 == 0) ) console.log(v); for(const v of lazy([1,2,3,4]) .filter(v=>v % 2 == 0) .map(v=>v*2) ) console.log(v);