함수 pipe 구현하는 방법

1 minute read
2024-07-21

rxjs 에는 pipe 라는 API 를 제공하고 있다. 각 순차 처리를 스트림 방식으로 처리하도록 한다.


스트림 처리는 아니더라도 순차적인 처리를 하는 것을 코드로 나타내기 좋을 때가 있다. framer-motion 에 좋은 코드가 있어 남긴다.


Github


코드

/**
 * Pipe
 * Compose other transformers to run linearily
 * pipe(min(20), max(40))
 * @param  {...functions} transformers
 * @return {function}
 */
const combineFunctions = (a: Function, b: Function) => (v: any) => b(a(v))
export const pipe = (...transformers: Function[]) =>
    transformers.reduce(combineFunctions)


HOF (High Order Function) 방식으로 처리하는 걸 볼 수 있다.


사용 예시

this.removeAccessibleListeners = pipe(
    removeKeydownListener,
    removeBlurListener
)


매우 깔끔하다.