Explorer
JavaScript

Write a function `pipe(...fns)` that returns a function that applies the functions from left to right (opposite of compose).

Problem Statement

<p>Write a function <code>pipe(...fns)</code> that returns a function that applies the functions from left to right (opposite of compose).</p>

Examples

Input: const add2 = x => x + 2, mult3 = x => x * 3; pipe(add2, mult3)(4)

Output: 18

Explanation: add2(4) = 6, then mult3(6) = 18.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Pipe is the opposite of compose — left-to-right instead of right-to-left. šŸ’” Hint 2: Use Array.reduce() instead of reduceRight. šŸ’” Hint 3: return (x) => fns.reduce((acc, fn) => fn(acc), x);

Editorial & Approach

Problem Overview & Intuition

To solve Pipe Function, we consider the execution characteristics of JavaScript engines. Write a function `pipe(...fns)` that returns a function that applies the functions from left to right (opposite of compose). By utilizing idiomatic language constructs and clean algorithmic principles, we can accomplish this with optimal time and memory usage.

Step-by-Step Approach

  1. Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
  2. Choose Core Mechanism: Use modern JavaScript patterns (pipe is the opposite of compose — left-to-right instead of right-to-left).
  3. Implement Logic: Handle state and transformations efficiently (use array.reduce() instead of reduceright).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function pipe(...fns) {
  return (x) => fns.reduce((acc, fn) => fn(acc), x);
}

Complexity Analysis

Time Complexity O(N) linear scan over input
Space Complexity O(1) constant auxiliary space (or O(N) output)

Edge Cases & Corner Traps Handled

  • Empty or boundary inputs (empty arrays, strings, zero length).
  • Type checks and unexpected values (e.g. null, undefined, negative numbers).
  • Closure preservation and memory isolation between separate invocations.

Pipe Function

Medium

Write a function pipe(...fns) that returns a function that applies the functions from left to right (opposite of compose).

Example Scenarios
1Example 1
Input: const add2 = x => x + 2, mult3 = x => x * 3; pipe(add2, mult3)(4)
Output: 18
Explanation:

add2(4) = 6, then mult3(6) = 18.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
[8,12]