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