Function Composition

Function Composition - Explanation

어려움 함수 O(n) O(1)

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

solution.js
function compose(...fns) {
  return x => fns.reduceRight((acc, fn) => fn(acc), x);
}

Key Concepts from This Problem

1. 함수 합성
2. reduceRight 메서드
3. 고차 함수
4. 클로저

Common Mistakes

reduce 대신 reduceRight를 사용해야 오른쪽에서 왼쪽으로 합성됩니다
초기값 x를 빠뜨리면 첫 함수가 초기값이 됩니다
반환되는 것이 값이 아닌 함수임을 기억하세요

Hints

Hint 1: reduceRight를 사용하세요.
Hint 2: 클로저를 활용하세요.

Complexity Analysis

Time Complexity

O(n)

Grows linearly with input size

Space Complexity

O(1)

Uses almost no additional memory

Related Tags

#함수 #합성 #고차함수