Explorer
JavaScript

Write a function `myAssign(target, ...sources)` that copies properties from source objects to the target object (shallow merge).

Problem Statement

<p>Write a function <code>myAssign(target, ...sources)</code> that copies properties from source objects to the target object (shallow merge).</p>

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

šŸ’” Hint 1: Iterate over each source object. šŸ’” Hint 2: For each source, copy all enumerable own properties to the target. šŸ’” Hint 3: Use Object.keys() on each source and assign to target.

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

  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 (iterate over each source object).
  3. Implement Logic: Handle state and transformations efficiently (for each source, copy all enumerable own properties to the target).
  4. 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

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 Object.assign

Medium

Write a function myAssign(target, ...sources) that copies properties from source objects to the target object (shallow merge).

Example Scenarios
1Example 1
Input: myAssign({ a: 1 }, { b: 2 }, { c: 3 })
Output: { a: 1, b: 2, c: 3 }
Explanation:

Properties are merged into the target object.

Editor
Loading Editor...
Evaluate code
Output:Click "Run" above to execute and verify your code here.
{"a":1,"b":2,"c":4,"d":5}