fix(util): fix assign polyfill

This commit is contained in:
Adam Bradley
2016-01-11 11:44:28 -06:00
parent b79d6cc8ea
commit 201c2dde67
2 changed files with 23 additions and 14 deletions

View File

@ -9,6 +9,19 @@ export function run() {
expect(obj).toEqual({ a: '1', b: '2', c: '0' }); expect(obj).toEqual({ a: '1', b: '2', c: '0' });
}); });
it('should extend complex', () => {
expect(util.assign(
{ a: '0', b: '0' },
{ b: '1', c: '1' },
{ c: '2', d: '2' }
)).toEqual({
a: '0',
b: '1',
c: '2',
d: '2'
});
});
}); });
describe('defaults', function() { describe('defaults', function() {

View File

@ -12,26 +12,22 @@ export function clamp(min, n, max) {
return Math.max(min, Math.min(n, max)); return Math.max(min, Math.min(n, max));
} }
// polyfill for Object.assign
var _assign: any;
if (typeof Object.assign !== 'function') {
// use the old-school shallow extend method
_assign = _baseExtend;
} else {
// use the built in ES6 Object.assign method
_assign = Object.assign;
}
/** /**
* The assign() method is used to copy the values of all enumerable own * The assign() method is used to copy the values of all enumerable own
* properties from one or more source objects to a target object. It will * properties from one or more source objects to a target object. It will
* return the target object. When available, this method will use * return the target object. When available, this method will use
* `Object.assign()` under-the-hood. * `Object.assign()` under-the-hood.
* @param target The target object * @param target The target object
* @param source The source object * @param source(s) The source object
*/ */
export function assign(target: any, source: any): any { export function assign(...args: any[]): any {
return _assign(target, source); if (typeof Object.assign !== 'function') {
// use the old-school shallow extend method
return _baseExtend(args[0], [].slice.call(args, 1), false);
}
// use the built in ES6 Object.assign method
return Object.assign.apply(null, args);
} }
/** /**
@ -43,7 +39,7 @@ export function merge(dst: any, ...args: any[]) {
return _baseExtend(dst, [].slice.call(arguments, 1), true); return _baseExtend(dst, [].slice.call(arguments, 1), true);
} }
function _baseExtend(dst, objs, deep = false) { function _baseExtend(dst, objs, deep) {
for (var i = 0, ii = objs.length; i < ii; ++i) { for (var i = 0, ii = objs.length; i < ii; ++i) {
var obj = objs[i]; var obj = objs[i];
if (!obj || !isObject(obj) && !isFunction(obj)) continue; if (!obj || !isObject(obj) && !isFunction(obj)) continue;