Write a function `myNew(Constructor, ...args)` that mimics the behavior of the `new` keyword.
Problem Statement
Examples
Input: myNew(Person, "Alice", 30)
Output: New instance with Person.prototype and initialized properties
Explanation: Simulates the `new` operator instantiation mechanism.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Implement new Operator, we consider the execution characteristics of JavaScript engines. Write a function `myNew(Constructor, ...args)` that mimics the behavior of the `new` keyword. 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 (new does 4 things: creates object, sets prototype, calls constructor, returns result).
- Implement Logic: Handle state and transformations efficiently (create an object with object.create(constructor.prototype)).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function myNew(Constructor, ...args) {
const obj = Object.create(Constructor.prototype);
const result = Constructor.apply(obj, args);
return typeof result === "object" && result !== null ? result : obj;
}
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.