FrontendInterviews.dev

Loading problem…

144. Object.assign (Polyfill)

Medium•

Implement Object.myAssign — a polyfill that behaves like native Object.assign for common interview scenarios.

Object.assign(target, ...sources) copies enumerable own properties from each source to the target object and returns the target.

Requirements

1) Core Behavior

  • Signature: Object.myAssign(target, ...sources)
  • Throw TypeError if target is null or undefined.
  • Convert target to an object and mutate that object.
  • For each source (left to right), copy its own enumerable properties into target.
  • Return the mutated target object reference.

2) Property Rules

  • Copy only own enumerable properties.
  • Copy both string keys and symbol keys.
  • Ignore inherited properties.
  • Ignore non-enumerable properties.

3) Source Handling + Edge Cases

  • Skip null and undefined sources.
  • Box primitive sources ('abc', true, 42) and copy any enumerable own props (e.g. string indices).
  • Later sources overwrite earlier keys.
  • If reading/writing a property throws, propagate the error and stop copying further properties/sources.

Example

const target = { a: 1 };
const source1 = { b: 2 };
const source2 = { a: 3, c: 4 };

Object.myAssign(target, source1, source2);
// { a: 3, b: 2, c: 4 }

Constraints

  • Must not use native Object.assign internally.
  • If target is null/undefined, throw TypeError.
  • Copy own enumerable string keys and symbol keys only.
  • Skip null/undefined sources.
  • Preserve left-to-right overwrite semantics.
  • Return the same target reference (after object coercion if primitive target).
Accepted16/19|Acceptance Rate84.2%