https://bigfrontend.dev/problem/implement-object-assign
The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object. (source: MDN)
It is widely used, Object Spread operator actually is internally the same as Object.assign() (source). Following 2 lines of code are totally the same.
let aClone = { ...a };
let aClone = Object.assign({}, a);This is an easy one, could you implement Object.assign() with your own implementation?
/**
* @param {any} target
* @param {any[]} sources
* @return {object}
*/
function objectAssign(target, ...sources) {
if (!target) {
throw new Error();
}
if (typeof target !== 'object') {
const constructor = Object.getPrototypeOf(target).constructor;
target = new constructor(target);
}
for (const source of sources) {
if (!source) {
continue;
}
const keys = [
...Object.keys(source),
...Object.getOwnPropertySymbols(source),
];
for (const key of keys) {
const descriptor = Object.getOwnPropertyDescriptor(target, key);
if (descriptor && !descriptor.configurable) {
throw new Error();
}
target[key] = source[key];
}
}
return target;
}