polyfills/Assign.js

/**
 * @module Polyfills
 */

/**
 * Polyfill for the native `Object.assign( target, ...sources )` function.
 * Copies source object(s) into target. Useful for copying or extending JS objects.
 * More info here: [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
 */

const Assign = {
	polyfill() {
		if ( typeof Object.assign !== 'function' ) {
			// Must be writable: true, enumerable: false, configurable: true
			Object.defineProperty( Object, 'assign', {
				value: function assign( target, ...varArgs ) { // .length of function is 2
					if ( null === target || undefined === target ) {
						throw new TypeError( 'Cannot convert undefined or null to object' );
					}

					const to = Object( target );

					for ( let index = 1; index < varArgs.length; index += 1 ) {
						const nextSource = varArgs[index];

						if ( null !== nextSource && undefined !== nextSource ) {
							Object.keys( nextSource ).forEach( ( nextKey ) => {
								to[nextKey] = nextSource[nextKey];
							});
						}
					}
					return to;
				},
				writable: true,
				configurable: true,
			});
		}
	},
};

export default Assign;