This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity posts.
AI solution for JavaScript Coding Question on BFE.dev
26. implement Object.assign()
Sure, here is an implementation of Object.assign():
function myAssign(target, ...sources) { for (let source of sources) { for (let key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key]; } } } return target;}
Here's an explanation of how it works:
- The
myAssign()function takes atargetobject (the object that properties will be copied to), and one or moresourceobjects (the objects that properties will be copied from). - We use the
for...ofloop to iterate over all thesourceobjects that were passed tomyAssign(). - For each
sourceobject, we use afor...inloop to iterate over all the properties of thesourceobject. - We use the
hasOwnProperty()method to check if the current property is actually a property of thesourceobject, and not inherited from its prototype. - If the current property is a property of the
sourceobject, we copy it to thetargetobject usingtarget[key] = source[key]. - Finally, we return the
targetobject that now has all the copied properties.
With this implementation, we can use myAssign() just like we would use Object.assign(). For example:
const obj1 = { a: 1 };const obj2 = { b: 2 };const obj3 = { c: 3 };const newObj = myAssign({}, obj1, obj2, obj3);console.log(newObj); // { a: 1, b: 2, c: 3 }
I hope this helps! Let me know if you have any questions.