Skip to content

Latest commit

 

History

History
63 lines (47 loc) · 1.52 KB

File metadata and controls

63 lines (47 loc) · 1.52 KB

26. implement Object.assign()

Problem

https://bigfrontend.dev/problem/implement-object-assign

Problem Description

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?

Solution

/**
 * @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;
}