Function Composition
Function Composition - Explanation
Problem Summary
Write a function that composes multiple functions from right to left.
Go to Problem →Detailed Explanation
이 문제는 **함수형 프로그래밍**의 핵심 개념인 **함수 합성(composition)**을 학습합니다. **함수 합성이란?** 여러 함수를 연결하여 하나의 새로운 함수를 만드는 것입니다. 수학의 f(g(x))와 같습니다. **compose의 동작 방식** 오른쪽에서 왼쪽으로 함수를 적용합니다: compose(f, g, h)(x) = f(g(h(x))) **compose(x => x * 2, x => x + 1)(5) 실행** 1. 오른쪽 함수 먼저: 5 + 1 = 6 2. 왼쪽 함수 적용: 6 * 2 = 12 **reduceRight의 역할** reduceRight는 배열을 오른쪽부터 순회합니다: - 초기값: x (입력값) - 각 단계: 이전 결과에 현재 함수 적용 **클로저 활용** compose는 함수를 반환합니다. 반환된 함수는 원래의 fns 배열에 접근할 수 있습니다 (클로저). **실용적 활용** ```javascript const addTax = x => x * 1.1; const addShipping = x => x + 5; const formatPrice = x => '$' + x.toFixed(2); const calculateTotal = compose(formatPrice, addShipping, addTax); calculateTotal(100); // "$115.00" ``` **pipe vs compose** pipe는 왼쪽에서 오른쪽, compose는 오른쪽에서 왼쪽입니다.
Solution Code
function compose(...fns) {
return x => fns.reduceRight((acc, fn) => fn(acc), x);
}Key Concepts from This Problem
Common Mistakes
Hints
Complexity Analysis
Time Complexity
O(n)
Grows linearly with input size
Space Complexity
O(1)
Uses almost no additional memory