Skip to content

Commit

Permalink
Merge pull request #454 from pistacchio/master
Browse files Browse the repository at this point in the history
Added default value to `_.result`.
  • Loading branch information
jdalton committed Jan 17, 2014
2 parents 8cffc77 + fc2135d commit 3ce47fb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
10 changes: 7 additions & 3 deletions lodash.js
Original file line number Diff line number Diff line change
Expand Up @@ -7247,13 +7247,14 @@
* Resolves the value of property `key` on `object`. If `key` is a function
* it will be invoked with the `this` binding of `object` and its result returned,
* else the property value is returned. If `object` is falsey then `undefined`
* is returned.
* is returned. If property `key` is not set, return defaultValue if defined;
*
* @static
* @memberOf _
* @category Utilities
* @param {Object} object The object to inspect.
* @param {string} key The name of the property to resolve.
* @param {*} [defaultValue] The value to return if object doesn't have key.
* @returns {*} Returns the resolved value.
* @example
*
Expand All @@ -7269,10 +7270,13 @@
*
* _.result(object, 'stuff');
* // => 'nonsense'
* _.result(object, 'pizza', 'spaghetti');
* // => 'spaghetti'
*/
function result(object, key) {
function result(object, key, defaultValue) {
if (object) {
var value = object[key];
var value = typeof object[key] !== 'undefined' ? object[key] : defaultValue;
return isFunction(value) ? object[key]() : value;
}
}
Expand Down
11 changes: 11 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6600,6 +6600,17 @@

deepEqual(actual, expected);
});

test('should return the default value if key is not found', 2, function() {
var object = {
'a': 1,
'b': 2
}

strictEqual(_.result(object, 'c', 3), 3);
strictEqual(_.result(object, 'c'), undefined);
});

}());

/*--------------------------------------------------------------------------*/
Expand Down

0 comments on commit 3ce47fb

Please sign in to comment.