🛠️ 처음부터 만드는 Compose — 오른쪽에서 왼쪽으로 함수를 합성하는 패턴
Compose vs Pipe
`Pipe`는 왼쪽에서 오른쪽으로 데이터를 흘려보내고, `Compose`는 오른쪽에서 왼쪽으로 함수를 중첩합니다. 함수형 프로그래밍에서 매우 자주 쓰입니다.
```javascript
// Compose: 우→좌 (함수 합성)
const compose = (...fns) => (x) => fns.reduceRight((acc, fn) => fn(acc), x);
// 8줄 완성!
```
사용 예시
```javascript
const add = (x) => x + 10;
const multiply = (x) => x * 2;
const square = (x) => x ** 2;
const calc = compose(add, multiply, square);
calc(5); // square(5) → multiply(25) → add(50) = 60
```
Pipe와의 차이
```javascript
// Pipe: 5 → square → multiply → add (왼쪽→오른쪽)
pipe(5, square, multiply, add); // 60
// Compose: add(multiply(square(5))) (우→좌, 수학 표기법)
compose(add, multiply, square)(5); // 60
```
실전: React 컴포넌트 체인
```javascript
const withTheme = (Component) => (props) => (/* ... */);
const withAuth = (Component) => (props) => (/* ... */);
const withLogging = (Component) => (props) => (/* ... */);
// Compose로 여러 HOC 조합
const enhance = compose(withTheme, withAuth, withLogging);
const EnhancedComponent = enhance(MyComponent);
```
함수형 프로그래밍의 핵심 패턴입니다. 선언적이고 조합 가능한 코드를 만드세요!
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!