diablero13
1/24/2018 - 7:03 AM

assignment.js

/**
*
* Oiginal reporitory: https://github.com/bevacqua/assignment
*
* Assign property objects onto other objects, recursively
* 
* example: assignment(a, b, c, ...)
* 
* Assigns every property of b onto a. If the an object already exists on a that has one of b's properties, then assignment(a.prop, b.prop) will assign all child properties of b.prop onto a.prop. This happens recursively.
* Returns a.
* 
*/

'use strict';

function assignment (result) {
  var stack = Array.prototype.slice.call(arguments, 1);
  var item;
  var key;
  while (stack.length) {
    item = stack.shift();
    for (key in item) {
      if (item.hasOwnProperty(key)) {
        if (typeof result[key] === 'object' && result[key] && Object.prototype.toString.call(result[key]) !== '[object Array]') {
          if (typeof item[key] === 'object' && item[key] !== null) {
            result[key] = assignment({}, result[key], item[key]);
          } else {
            result[key] = item[key];
          }
        } else {
          result[key] = item[key];
        }
      }
    }
  }
  return result;
}

module.exports = assignment;