본문 바로가기
language/javascript

🪄 함수 합성(Compose, Pipe)과 Lodash 실전 예제

by 죄니안죄니 2025. 5. 11.

🪄 함수 합성(Compose, Pipe)과 Lodash 실전 예제

함수형 프로그래밍에서 핵심 개념 중 하나는 함수 합성(Function Composition)입니다.
여러 개의 함수를 조합하여 작고 단순한 함수 → 더 큰 동작을 만들어내는 방식입니다.
이번 글에서는 composepipe의 개념 차이와 함께 Lodash를 활용한 실전 예제를 정리합니다.


1. 함수 합성이란?

함수 f, g를 합성한다고 하면: f(g(x)) 형태로 동작합니다.
즉, g의 결과가 f의 입력으로 전달됩니다.


const toUpper = str => str.toUpperCase();
const exclaim = str => str + "!";

const shout = str => exclaim(toUpper(str));
console.log(shout("hello")); // 👉 "HELLO!"

2. compose vs pipe 차이

방향 compose pipe
적용 순서 오른쪽 → 왼쪽 왼쪽 → 오른쪽
표현 compose(f, g)(x) → f(g(x)) pipe(g, f)(x) → f(g(x))
가독성 수학적, 익숙한 개발자에 적합 일반적 읽기 흐름과 유사

3. Lodash에서의 pipe: _.flow


import _ from "lodash";

const toUpper = str => str.toUpperCase();
const exclaim = str => str + "!";
const repeat = str => str.repeat(2);

const process = _.flow(toUpper, exclaim, repeat);

console.log(process("hi")); // 👉 "HI!HI!"

_.flow왼쪽에서 오른쪽으로 함수 실행 – pipe 방식입니다.


4. Lodash/fp: _.compose도 제공


import { compose } from "lodash/fp";

const shout = compose(
  str => str + "!",
  str => str.toUpperCase()
);

console.log(shout("hello")); // 👉 "HELLO!"

lodash/fp불변성과 함수형 패턴 중심으로 제공되는 별도 모듈입니다.


5. 실전 예제 – 유저 데이터 정제


const normalizeUser = _.flow([
  user => ({ ...user, name: user.name.trim() }),
  user => ({ ...user, name: user.name.toLowerCase() }),
  user => ({ ...user, isAdult: user.age >= 18 })
]);

const raw = { name: "  Alice  ", age: 20 };
console.log(normalizeUser(raw));
// 👉 { name: "alice", age: 20, isAdult: true }

작은 함수들을 조합하여 하나의 큰 함수로 구성 – 선언형 코드의 대표 패턴입니다.


6. 함수 합성 커스텀 구현 (pipe)


const pipe = (...fns) => input =>
  fns.reduce((acc, fn) => fn(acc), input);

const result = pipe(
  x => x + 1,
  x => x * 2,
  x => `Result: ${x}`
)(3);

console.log(result); // 👉 "Result: 8"

📌 마무리

composepipe함수를 조합하여 읽기 좋은 코드를 만드는 데 필수적인 패턴입니다.
특히 불변성을 유지하면서 복잡한 변환 로직을 단순화할 수 있어, map/filter와 함께 실무에서 자주 사용됩니다.

다음 글에서는 순수 함수, 불변성, 사이드 이펙

댓글