Explorer
JavaScript

Write a simplified `MyPromise` constructor that supports `.then()` chaining and basic resolve/reject.

Problem Statement

<p>Write a simplified <code>MyPromise</code> constructor that supports <code>.then()</code> chaining and basic resolve/reject.</p>

Examples

Input: new MyPromise(resolve => resolve(42)).then(val => val * 2)

Output: 8

Explanation: Asynchronously chains `.then()` callbacks.

Complexity

Time Complexity: O(N)

Space Complexity: O(1)

Hints

šŸ’” Hint 1: Store callbacks for then. When resolved, call them. šŸ’” Hint 2: Handle the case where resolve is called before .then() is attached (store the value). šŸ’” Hint 3: then() should return a new MyPromise for chaining.

Editorial & Approach

Problem Overview & Intuition

To solve Implement Promise (Simplified), we consider the execution characteristics of JavaScript engines. Write a simplified `MyPromise` constructor that supports `.then()` chaining and basic resolve/reject. 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 (store callbacks for then. when resolved, call them).
  3. Implement Logic: Handle state and transformations efficiently (handle the case where resolve is called before .then() is attached (store the value)).
  4. Return Result: Ensure proper return format and preserve caller context if applicable.

Optimal Implementation (JavaScript)

function MyPromise(executor) {
  let state = "pending";
  let value;
  let handlers = [];
  function resolve(result) {
    if (state !== "pending") return;
    state = "fulfilled";
    value = result;
    handlers.forEach(h => h.onFulfilled(value));
  }
  function reject(reason) {
    if (state !== "pending") return;
    state = "rejected";
    value = reason;
    handlers.forEach(h => h.onRejected(value));
  }
  this.then = function(onFulfilled, onRejected) {
    return new MyPromise((res, rej) => {
      const handle = {
        onFulfilled: val => {
          try { res(onFulfilled ? onFulfilled(val) : val); }
          catch (e) { rej(e); }
        },
        onRejected: reason => {
          try { if (onRejected) res(onRejected(reason)); else rej(reason); }
          catch (e) { rej(e); }
        }
      };
      if (state === "fulfilled") handle.onFulfilled(value);
      else if (state === "rejected") handle.onRejected(value);
      else handlers.push(handle);
    });
  };
  executor(resolve, reject);
}

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.

Implement Promise (Simplified)

Hard

Write a simplified MyPromise constructor that supports .then() chaining and basic resolve/reject.

Example Scenarios
1Example 1
Input: new MyPromise(resolve => resolve(42)).then(val => val * 2)
Output: 8
Explanation:

Asynchronously chains `.then()` callbacks.

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