From ce19ed529493f736f996afb63e6e3ffa2a732880 Mon Sep 17 00:00:00 2001 From: forbesjo Date: Thu, 16 Feb 2017 16:55:37 -0500 Subject: [PATCH] fix: make mergeOptions behave the same across browsers (#4090) * Make an object util function `keys` return an empty array for non objects * Use that function in object utils instead of `Object.assign` --- src/js/utils/obj.js | 20 ++++++++++++++++++-- test/unit/utils/merge-options.test.js | 7 +++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/js/utils/obj.js b/src/js/utils/obj.js index a6896e2712..17572dc7c6 100644 --- a/src/js/utils/obj.js +++ b/src/js/utils/obj.js @@ -30,6 +30,22 @@ */ const toString = Object.prototype.toString; +/** + * Get the keys of an Object + * + * @param {Object} + * The Object to get the keys from + * + * @return {string[]} + * An array of the keys from the object. Returns an empty array if the + * object passed in was invalid or had no keys. + * + * @private + */ +const keys = function(object) { + return isObject(object) ? Object.keys(object) : []; +}; + /** * Array-like iteration for objects. * @@ -40,7 +56,7 @@ const toString = Object.prototype.toString; * The callback function which is called for each key in the object. */ export function each(object, fn) { - Object.keys(object).forEach(key => fn(object[key], key)); + keys(object).forEach(key => fn(object[key], key)); } /** @@ -61,7 +77,7 @@ export function each(object, fn) { * The final accumulated value. */ export function reduce(object, fn, initial = 0) { - return Object.keys(object).reduce( + return keys(object).reduce( (accum, key) => fn(accum, object[key], key), initial); } diff --git a/test/unit/utils/merge-options.test.js b/test/unit/utils/merge-options.test.js index 6c07a3a233..aebffb5935 100644 --- a/test/unit/utils/merge-options.test.js +++ b/test/unit/utils/merge-options.test.js @@ -2,6 +2,7 @@ import mergeOptions from '../../../src/js/utils/merge-options.js'; QUnit.module('merge-options'); + QUnit.test('should merge options objects', function(assert) { const ob1 = { a: true, @@ -27,3 +28,9 @@ QUnit.test('should merge options objects', function(assert) { d: true }, 'options objects merged correctly'); }); + +QUnit.test('should ignore non-objects', function(assert) { + const obj = { a: 1 }; + + assert.deepEqual(mergeOptions(obj, true), obj, 'ignored non-object input'); +});