Write a function `myAssign(target, ...sources)` that copies properties from source objects to the target object (shallow merge).
Problem Statement
Examples
Input: myAssign({ a: 1 }, { b: 2 }, { c: 3 })
Output: { a: 1, b: 2, c: 3 }
Explanation: Properties are merged into the target object.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
To solve Implement Object.assign, we consider the execution characteristics of JavaScript engines. Write a function `myAssign(target, ...sources)` that copies properties from source objects to the target object (shallow merge). 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 (iterate over each source object).
- Implement Logic: Handle state and transformations efficiently (for each source, copy all enumerable own properties to the target).
- Return Result: Ensure proper return format and preserve caller context if applicable.
Optimal Implementation (JavaScript)
function myAssign(target, ...sources) {
for (const source of sources) {
if (source != null) {
for (const key of Object.keys(source)) {
target[key] = source[key];
}
}
}
return target;
}
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.