Explorer
JavaScript

Write a function `promiseRace(promises)` that resolves or rejects with the first settled promise.

Problem Statement

<p>Write a function <code>promiseRace(promises)</code> that resolves or rejects with the first settled promise.</p>

Examples

Input: promiseRace([slowPromise, fastPromise])

Output: Result of fastest promise

Explanation: Settles with the earliest settled promise.

Complexity

Time Complexity: O(N)

Space Complexity: O(N)

Hints

šŸ’” Hint 1: Return a new Promise. šŸ’” Hint 2: The first promise to resolve or reject should settle the outer promise. šŸ’” Hint 3: promises.forEach(p => Promise.resolve(p).then(resolve, reject));

Editorial & Approach

Problem Overview & Intuition

To solve Promise.race Implementation, we consider the execution characteristics of JavaScript engines. Write a function `promiseRace(promises)` that resolves or rejects with the first settled promise. 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 (return a new promise).
  3. Implement Logic: Handle state and transformations efficiently (the first promise to resolve or reject should settle the outer promise).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function promiseRace(promises) {
  return new Promise((resolve, reject) => {
    promises.forEach(p => Promise.resolve(p).then(resolve, reject));
  });
}

Complexity Analysis

Time Complexity O(N) parallel promise registration
Space Complexity O(N) output buffer array

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.

Promise.race Implementation

Medium

Write a function promiseRace(promises) that resolves or rejects with the first settled promise.

Example Scenarios
1Example 1
Input: promiseRace([slowPromise, fastPromise])
Output: Result of fastest promise
Explanation:

Settles with the earliest settled promise.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
fast