TypeScript/νƒ€μž…μŠ€ν¬λ¦½νŠΈ TypeScript

[νƒ€μž…μŠ€ν¬λ¦½νŠΈ] μ œλ„ˆλ ˆμ΄ν„° 지원, λͺ…μ‹œ

Rainbow🌈Coder 2022. 4. 19. 12:57
728x90

μ œλ„ˆλ ˆμ΄ν„° ν•¨μˆ˜

μ œλ„ˆλ ˆμ΄ν„° ν•¨μˆ˜λŠ” μ—¬λŸ¬ 개의 값을 μƒμ„±ν•˜λŠ” νŽΈλ¦¬ν•œ κΈ°λŠ₯을 μ œκ³΅ν•œλ‹€. μ œλ„ˆλ ˆμ΄ν„° ν•¨μˆ˜λ₯Ό μ΄μš©ν•˜λ©΄ 값을 μƒμ‚°ν•˜λŠ” 속도도 μ •κ΅ν•˜κ²Œ μ‘°μ •ν•  수 μžˆλ‹€.

//λ‹€μŒ ν”Όλ³΄λ‚˜μΉ˜ 숫자λ₯Ό κ³„μ‚°ν•˜κΈ° μœ„ν•΄ a에 bλ₯Ό, b에 a+bλ₯Ό ν•œλ²ˆμ— λ‹€μ‹œ ν• λ‹Ήν•œλ‹€.

function* createFibonacciGenerator() {
  let a = 0;
  let b = 1;
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

let fiboancciGenerator = createFibonacciGenerator();
                                        //IterableIterator<number>
console.log(fiboancciGenerator.next()); //{ value: 0, done: false }
console.log(fiboancciGenerator.next()); //{ value: 1, done: false }
console.log(fiboancciGenerator.next()); //{ value: 1, done: false }
console.log(fiboancciGenerator.next()); //{ value: 2, done: false }
console.log(fiboancciGenerator.next()); //{ value: 3, done: false }
console.log(fiboancciGenerator.next()); //{ value: 5, done: false }
console.log(fiboancciGenerator.next()); //{ value: 8, done: false }
console.log(fiboancciGenerator.next()); //{ value: 13, done: false }

μœ„ μ½”λ“œμ˜ createFibonacciGenerator ν•¨μˆ˜λŠ” IterableIterator을 λ°˜ν™˜ν•˜κ³ , 이 μ œλ„ˆλ ˆμ΄ν„°μ— nextλ₯Ό ν˜ΈμΆœν•  λ•Œλ§ˆλ‹€ λ‹€μŒ ν”Όλ³΄λ‚˜μΉ˜ 값을 κ³„μ‚°ν•΄μ„œ κ²°κ³Όλ₯Ό λ°©μΆœν•œλ‹€. νƒ€μž…μŠ€ν¬λ¦½νŠΈμ—μ„œ 방좜된 값을 μ΄μš©ν•΄ 반볡자의 νƒ€μž…μ„ μΆ”λ‘ ν•œλ‹€.

 

λ‹€μŒ 예처럼 IterableIterator μ—μ„œ λ°©μΆœν•˜λŠ” νƒ€μž…μ„ κ°μ‹Έμ„œ μ œλ„ˆλ ˆμ΄ν„° λ°˜ν™˜ νƒ€μž…μ„ λͺ…μ‹œν•˜λŠ” 방법도 μžˆλ‹€.

function* createNumbers(): IterableIterator<number> {
  let n = 1;
  while (true) {
    yield n++;
  }
}
let numbers = createNumbers();
console.log(numbers.next()); //{ value: 1, done: false }
console.log(numbers.next()); //{ value: 2, done: false }
console.log(numbers.next()); //{ value: 3, done: false }

 

μš”μ•½ν•˜μžλ©΄ μ œλ„ˆλ ˆμ΄ν„°λŠ” μžλ°”μŠ€ν¬λ¦½νŠΈμ˜ 정말 λ©‹μ§„ κΈ°λŠ₯이며 νƒ€μž…μŠ€ν¬λ¦½νŠΈμ—μ„œλ„ μ§€μ›ν•œλ‹€λŠ” 사싀이닀.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

728x90