UNPKG

101

Version:

common javascript utils that can be required selectively that assume es5+

43 lines (41 loc) 1.82 kB
/** * @module 101/assign */ /** * Copies enumerable and own properties from a source object(s) to a target object, aka extend. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign * I added functionality to support assign as a partial function * @function module:101/assign * @param {object} [target] - object which source objects are extending (being assigned to) * @param {object} sources... - objects whose properties are being assigned to the source object * @return {object} source with extended properties */ module.exports = assign; function assign (target, firstSource) { if (arguments.length === 1) { firstSource = arguments[0]; return function (target) { return assign(target, firstSource); }; } if (target === undefined || target === null) throw new TypeError('Cannot convert first argument to object'); var to = Object(target); for (var i = 1; i < arguments.length; i++) { var nextSource = arguments[i]; if (nextSource === undefined || nextSource === null) continue; var keysArray = Object.keys(Object(nextSource)); for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) { var nextKey = keysArray[nextIndex]; Object.getOwnPropertyDescriptor(nextSource, nextKey); // I changed the following line to get 100% test coverage. // if (desc !== undefined && desc.enumerable) to[nextKey] = nextSource[nextKey]; // I was unable to find a scenario where desc was undefined or that desc.enumerable was false: // 1) Object.defineProperty does not accept undefined as a desc // 2) Object.keys does not return non-enumerable keys. // Let me know if this is a cross browser thing. to[nextKey] = nextSource[nextKey]; } } return to; }