📖 전예홍, ⌈Do it! 타입스크립트 프로그래밍⌋, 이지스퍼블리싱, 2021
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)))
)
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)로 작성해야 한다는 것을 암기했다.