From a75e18855a67f51ab24903f3f81a18bf9382c34b Mon Sep 17 00:00:00 2001 From: "luca.campli" Date: Sat, 30 Dec 2017 20:09:14 +0530 Subject: [PATCH] add null checks and tests relative to the solved issues --- index.js | 5 +++-- test/dot-prop-immutable.spec.js | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index c1a0eb9..1edf4c8 100644 --- a/index.js +++ b/index.js @@ -33,12 +33,13 @@ function set(obj, prop, value) { * Get a value by a dot path. * @param obj The object to evaluate. * @param prop The path to value that should be returned. + * @param value The default value that should be returned when the target doesn't exist. */ function get(obj, prop, value) { prop = typeof prop === 'number' ? propToArray(prop.toString()) : typeof prop === 'string' ? propToArray(prop) : prop; for (var i = 0; i < prop.length; i++) { - if (typeof obj !== 'object') { + if (obj === null || typeof obj !== 'object') { return value; } var head = prop[i]; @@ -69,7 +70,7 @@ function _delete(obj, prop) { var deletePropImmutableRec = function(obj, prop, i) { var clone, head = prop[i]; - if (typeof obj !== 'object' || + if (obj === null || typeof obj !== 'object' || !Array.isArray(obj) && obj[head] === undefined) { return obj; diff --git a/test/dot-prop-immutable.spec.js b/test/dot-prop-immutable.spec.js index eed52e2..3d0c46b 100644 --- a/test/dot-prop-immutable.spec.js +++ b/test/dot-prop-immutable.spec.js @@ -357,6 +357,14 @@ describe('dot-prop-immutable.spec.js', function() { }); }); + describe('when get intermediate deep prop is null', () => { + + it('should return default value', () => { + expect(dotProp.get({b: {z: null}}, 'b.z.w')).to.equal(undefined); + expect(dotProp.get({b: {z: null}}, 'b.z.w', 'default')).to.equal('default'); + }); + }); + describe('when get array[index]', () => { it('should get index', () => { @@ -509,6 +517,17 @@ describe('dot-prop-immutable.spec.js', function() { it('invariant', objInvariant); }); + describe('when delete deep prop is null', () => { + + before(function () { + result = dotProp.delete({b: {z: null}}, 'b.z.w'); + }); + + it('should delete prop', () => { + expect(result).to.eql({b: {z: null}}); + }); + }); + describe('when delete array[index]', () => { before(function () {