Skip to content

Commit 59ed89e

Browse files
authored
Merge pull request #15799 from deepesh224-ux/master
Fix: Robust Null Safety for Internal Utility Functions
2 parents 638c3c0 + cfcec53 commit 59ed89e

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

lib/utils.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -190,6 +190,9 @@ exports.deepEqual = function deepEqual(a, b) {
190190
*/
191191

192192
exports.last = function(arr) {
193+
if (arr == null) {
194+
return void 0;
195+
}
193196
if (arr.length > 0) {
194197
return arr[arr.length - 1];
195198
}
@@ -272,6 +275,10 @@ exports.clonePOJOsAndArrays = function clonePOJOsAndArrays(val) {
272275
exports.merge = function merge(to, from, options, path) {
273276
options = options || {};
274277

278+
if (from == null) {
279+
return to;
280+
}
281+
275282
const keys = Object.keys(from);
276283
let i = 0;
277284
const len = keys.length;
@@ -690,6 +697,9 @@ exports.setValue = function(path, val, obj, map, _copying) {
690697

691698
exports.object = {};
692699
exports.object.vals = function vals(o) {
700+
if (o == null) {
701+
return [];
702+
}
693703
const keys = Object.keys(o);
694704
let i = keys.length;
695705
const ret = [];

test/utils.test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,4 +351,26 @@ describe('utils', function() {
351351
assert.equal(utils.toCollectionName('test', pluralize), 'tests');
352352
});
353353
});
354+
355+
describe('null checks', function() {
356+
// regression test: previously these would crash with "Cannot read property 'length' of null"
357+
// or similar errors. now they should fail gracefully.
358+
it('utils.last() handles null/undefined inputs', function() {
359+
assert.strictEqual(utils.last(null), undefined);
360+
assert.strictEqual(utils.last(undefined), undefined);
361+
});
362+
363+
// merge shouldn't blow up if the source object is missing
364+
it('utils.merge() returns target if source is null/undefined', function() {
365+
const target = { foo: 'bar' };
366+
assert.strictEqual(utils.merge(target, null), target);
367+
assert.strictEqual(utils.merge(target, undefined), target);
368+
});
369+
370+
// just return empty array if we can't get values from nothing
371+
it('utils.object.vals() returns empty array for null/undefined', function() {
372+
assert.deepStrictEqual(utils.object.vals(null), []);
373+
assert.deepStrictEqual(utils.object.vals(undefined), []);
374+
});
375+
});
354376
});

0 commit comments

Comments
 (0)