08장 함수 조합의 원리와 응용

Iris·2022년 1월 14일
0
post-thumbnail

📖 전예홍, ⌈Do it! 타입스크립트 프로그래밍⌋, 이지스퍼블리싱, 2021

08-4 함수 조합

compose 함수

export const f = <T>(x: T): string => `f(${x})`
export const g = <T>(x: T): string => `g(${x})`
export const h = <T>(x: T): string => `h(${x})`
export const compose = <T, R>(...functions: readonly Function[]): Function => (x: T): (T) => R => {
  const deepCopiedFunctions = [...functions]
  return deepCopiedFunctions.reverse().reduce((value, func) => func(value), x)
}
import {f, g, h} from './f-g-h'
import {compose} from './compose'

const composedFGH = compose(h, g, f)
console.log(
  composedFGH('x') // h(g(f(x)))
)

pipe 함수

export const pipe = <T>(...functions: readonly Function[]): Function => (x: T): T => {
  return functions.reduce((value, func) => func(value), x)
}
import {f, g, h} from './f-g-h'
import {pipe} from './pipe'

const piped = pipe(f, g, h)
console.log(
  piped('x') // h(g(f(x)))
)

이번 스터디에서 특별히 좋았던 점이나 어려웠던 점, 새로 알게 된 부분

함수 조합의 의미를 이해하고, compose 혹은 pipe 함수를 이용하여 함수 조합을 구현하는 방법을 학습했다. h(g(f(x))) 수식을 compose 함수는 compose(h, g, f)의 형태로, pipe 함수는 pipe(f, g, h)로 작성해야 한다는 것을 암기했다.

profile
👩🏻‍💻 Web Front-end Developer

0개의 댓글