Write a simplified `MyPromise` constructor that supports `.then()` chaining and basic resolve/reject.
Problem Statement
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
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
- Understand Problem Contract: Identify input arguments, return type expectations, and edge cases (empty inputs, nullish values).
- Choose Core Mechanism: Use modern JavaScript patterns (store callbacks for then. when resolved, call them).
- Implement Logic: Handle state and transformations efficiently (handle the case where resolve is called before .then() is attached (store the value)).
- 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
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.