Q15: Implement a polyfill for Object.assign().
Answer
Object.assign() copies enumerable own properties from one or more source objects into a target object. It returns the target object and performs a shallow copy.
if (!Object.myAssign) {
Object.myAssign = function (target, ...sources) {
if (target == null) {
throw new TypeError("Cannot convert undefined or null to object");
}
const output = Object(target);
for (const source of sources) {
if (source == null) {
continue;
}
const from = Object(source);
for (const key of Reflect.ownKeys(from)) {
const descriptor = Object.getOwnPropertyDescriptor(from, key);
if (descriptor && descriptor.enumerable) {
output[key] = from[key];
}
}
}
return output;
};
}
const target = { a: 1 };
const source = { b: 2 };
console.log(Object.myAssign(target, source));
// { a: 1, b: 2 }
Explanation
- Reject a nullish target.
- Convert the target into an object.
- Process each source object.
- Read its own property keys, including symbols.
- Copy enumerable properties to the target.
- Return the target object.
Interview notes
Object.assign() is shallow: nested objects remain shared references. It reads source property values and writes to the target, so getters and setters can execute. A production implementation should preserve native error and property-copy semantics carefully.
Key Takeaways
- Object.assign copies enumerable own properties and returns the target.
- The copy is shallow, and symbol properties can also be copied.