Update _.result to execute default values if they're functions.

This commit is contained in:
John-David Dalton
2014-12-10 23:28:32 -08:00
parent 94fd20e864
commit cd5f9b8bd4
2 changed files with 16 additions and 14 deletions

View File

@@ -10040,11 +10040,10 @@
} }
/** /**
* Resolves the value of property `key` on `object`. If `key` is a function * Resolves the value of property `key` on `object`. If the value of `key` is
* it is invoked with the `this` binding of `object` and its result returned, * a function it is invoked with the `this` binding of `object` and its result
* else the property value is returned. If `object` is `null` or `undefined` * is returned, else the property value is returned. If the property value is
* then `undefined` is returned. If a default value is provided it is returned * `undefined` the `defaultValue` is used in its place.
* if the property value resolves to `undefined`.
* *
* @static * @static
* @memberOf _ * @memberOf _
@@ -10056,12 +10055,7 @@
* @returns {*} Returns the resolved value. * @returns {*} Returns the resolved value.
* @example * @example
* *
* var object = { * var object = { 'user': 'fred', 'age': _.constant(40) };
* 'user': 'fred',
* 'age': function() {
* return 40;
* }
* };
* *
* _.result(object, 'user'); * _.result(object, 'user');
* // => 'fred' * // => 'fred'
@@ -10071,13 +10065,16 @@
* *
* _.result(object, 'status', 'busy'); * _.result(object, 'status', 'busy');
* // => 'busy' * // => 'busy'
*
* _.result(object, 'status', _.constant('busy'));
* // => 'busy'
*/ */
function result(object, key, defaultValue) { function result(object, key, defaultValue) {
var value = object == null ? undefined : object[key]; var value = object == null ? undefined : object[key];
if (typeof value == 'undefined') { if (typeof value == 'undefined') {
return defaultValue; value = defaultValue;
} }
return isFunction(value) ? object[key]() : value; return isFunction(value) ? value.call(object) : value;
} }
/** /**

View File

@@ -10374,7 +10374,7 @@
}); });
test('should return the specified default value for undefined properties', 1, function() { test('should return the specified default value for undefined properties', 1, function() {
var values = empties.concat(true, new Date, _.constant(1), 1, /x/, 'a'); var values = empties.concat(true, new Date, 1, /x/, 'a');
var expected = _.transform(values, function(result, value) { var expected = _.transform(values, function(result, value) {
result.push(value, value); result.push(value, value);
@@ -10389,6 +10389,11 @@
deepEqual(actual, expected); deepEqual(actual, expected);
}); });
test('should execute default function values', 1, function() {
var actual = _.result(object, 'd', object.c);
strictEqual(actual, 1);
});
}()); }());
/*--------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------*/