Lazy Execution - ChoDragon9/posts GitHub Wiki
Generator
λ₯Ό μ¬μ©νμ¬ Coroutine
μ μ¬μ©ν κ²κ³Ό κΈ°μ‘΄μ μ¬μ©ν Call Stack
μ μ°¨μ΄λ₯Ό μ€λͺ
νλ€.
Call Stack
function odd(arr) {
const newArr = []
for (const v of arr) {
console.log(`odd ${v}`)
if (v % 2) {
newArr.push(v)
}
}
return newArr
}
function take(arr, n) {
const newArr = []
let count = 0
for (const v of arr) {
console.log(`take ${v}`)
count++
newArr.push(v)
if (count === n) {
break;
}
}
return newArr
}
μ€μ²©ν¨μ μ€ λ΄λΆμ μ¬μ©λ odd
κ° μ€νλ λ€, take
κ° μ€νλλ€. λ°°μ΄μ ν¬κΈ°λ§νΌ 루νκ° λ°λ³΅λλ κ²μ μ μ μλ€.
const arr = [0,1,2,3,4,5]
console.log(...take(odd(arr), 2))
// odd 0
// odd 1
// odd 2
// odd 3
// odd 4
// odd 5
// take 1
// take 3
// 1 3
Coroutine
function* odd(arr) {
for (const v of arr) {
console.log(`odd ${v}`)
if (v % 2) {
yield v
}
}
}
function* take(arr, n) {
let count = 0
for (const v of arr) {
console.log(`take ${v}`)
count++
yield v
if (count === n) {
break;
}
}
}
Generator
λ₯Ό μ¬μ©νλ©΄ odd
μμ yield
λ₯Ό λ§λλ©΄ take
λ‘ μ»€μκ° μ΄λλκ³ take
μμ yield
λ₯Ό μ¬μ©νλ©΄ odd
λ‘ μ»€μκ° μ΄λλλ€.
μ΄λ¬ν μμ
μ΄ λ°λ³΅ λ λ€ break
λ₯Ό λ§λκ² λλ©΄ done
μ λ°ννμ¬ λ£¨νκ° μ’
λ£νκ² λλ€.
const arr = [0,1,2,3,4,5]
console.log(...take(odd(arr), 2))
// odd 0
// odd 1
// take 1
// odd 2
// odd 3
// take 3
// 1 3