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 atarget
object (the object that properties will be copied to), and one or moresource
objects (the objects that properties will be copied from). - We use the
for...of
loop to iterate over all thesource
objects that were passed tomyAssign()
. - For each
source
object, we use afor...in
loop to iterate over all the properties of thesource
object. - We use the
hasOwnProperty()
method to check if the current property is actually a property of thesource
object, and not inherited from its prototype. - If the current property is a property of the
source
object, we copy it to thetarget
object usingtarget[key] = source[key]
. - Finally, we return the
target
object 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.