Web Dev/1. JS 문법 관련
yield * 사용법
hYhY1234
2021. 2. 3. 10:39
728x90
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield*
yield* - JavaScript | MDN
The yield* expression is used to delegate to another generator or iterable object. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/md
developer.mozilla.org
L.deepFlat([
[1, 2, [22, 23, 24, [33, 34, 35]]],
3,
4,
[5, 6],
[7, 8, 9],
]);
위의 코드는 모든 원소를 쭉 펼치는 코드인데, 배열안에배열이 있는 경우에는 yield* 를 통해서 펼칠 수 있다.
yield* 는 iterable object를 반환하는데,
mdn문서의 예제에 따르면 아래와 같이 사용된다.
function* g1() {
yield 2;
yield 3;
yield 4;
}
function* g2() {
yield 1;
yield* g1();
yield 5;
}
const iterator = g2();
console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: 4, done: false}
console.log(iterator.next()); // {value: 5, done: false}
console.log(iterator.next()); // {value: undefined, done: true}
그렇기 때문에 아래처럼 제너레이터를 반환하도록 하면서 순환호출을해서 flatten을 수행할 수 있다.
const isIterable = (a) => a && a[Symbol.iterator];
L.deepFlat = function* f(iter) {
for (const a of iter) {
if (isIterable(a)) {
yield* f(a);
} else {
yield a;
}
}
};