Skip to content

Commit 2568ae0

Browse files
committed
Merge pull request #1515 from nhunzaker/master
Provide default value to result method. Fix #1495
2 parents 6b879c4 + fe7f523 commit 2568ae0

File tree

2 files changed

+33
-4
lines changed

2 files changed

+33
-4
lines changed

test/utility.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,33 @@
270270
strictEqual(_.result(null, 'x'), undefined);
271271
});
272272

273+
test('result returns a default value if object is null or undefined', function() {
274+
strictEqual(_.result(null, 'b', 'default'), 'default');
275+
strictEqual(_.result(undefined, 'c', 'default'), 'default');
276+
strictEqual(_.result(''.match('missing'), 1, 'default'), 'default');
277+
});
278+
279+
test('result returns a default value if property of object is missing', function() {
280+
strictEqual(_.result({d: null}, 'd', 'default'), null);
281+
strictEqual(_.result({e: false}, 'e', 'default'), false);
282+
});
283+
284+
test('result only returns the default value if the object does not have the property or is undefined', function() {
285+
strictEqual(_.result({}, 'b', 'default'), 'default');
286+
strictEqual(_.result({d: undefined}, 'd', 'default'), 'default');
287+
});
288+
289+
test('result does not return the default if the property of an object is found in the prototype', function() {
290+
var Foo = function(){};
291+
Foo.prototype.bar = 1;
292+
strictEqual(_.result(new Foo, 'bar', 2), 1);
293+
});
294+
295+
test('result does use the fallback when the result of invoking the property is undefined', function() {
296+
var obj = {a: function() {}};
297+
strictEqual(_.result(obj, 'a', 'failed'), undefined);
298+
});
299+
273300
test('_.templateSettings.variable', function() {
274301
var s = '<%=data.x%>';
275302
var data = {x: 'x'};

underscore.js

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -861,7 +861,7 @@
861861
if (nativeKeys) return nativeKeys(obj);
862862
var keys = [];
863863
for (var key in obj) if (_.has(obj, key)) keys.push(key);
864-
864+
865865
// Ahem, Internet Explorer.
866866
if (hasEnumBug) {
867867
var nonEnumIdx = nonEnumerableProps.length;
@@ -1260,9 +1260,11 @@
12601260

12611261
// If the value of the named `property` is a function then invoke it with the
12621262
// `object` as context; otherwise, return it.
1263-
_.result = function(object, property) {
1264-
if (object == null) return void 0;
1265-
var value = object[property];
1263+
_.result = function(object, property, fallback) {
1264+
var value = object == null ? void 0 : object[property];
1265+
if (value === void 0) {
1266+
return fallback;
1267+
}
12661268
return _.isFunction(value) ? object[property]() : value;
12671269
};
12681270

0 commit comments

Comments
 (0)