From cd5f9b8bd4a563cd9e78886934d60b958db1110e Mon Sep 17 00:00:00 2001 From: John-David Dalton Date: Wed, 10 Dec 2014 23:28:32 -0800 Subject: [PATCH] Update `_.result` to execute default values if they're functions. --- lodash.js | 23 ++++++++++------------- test/test.js | 7 ++++++- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/lodash.js b/lodash.js index 75809a729..fee83a99e 100644 --- a/lodash.js +++ b/lodash.js @@ -10040,11 +10040,10 @@ } /** - * Resolves the value of property `key` on `object`. If `key` is a function - * it is invoked with the `this` binding of `object` and its result returned, - * else the property value is returned. If `object` is `null` or `undefined` - * then `undefined` is returned. If a default value is provided it is returned - * if the property value resolves to `undefined`. + * Resolves the value of property `key` on `object`. If the value of `key` is + * a function it is invoked with the `this` binding of `object` and its result + * is returned, else the property value is returned. If the property value is + * `undefined` the `defaultValue` is used in its place. * * @static * @memberOf _ @@ -10056,12 +10055,7 @@ * @returns {*} Returns the resolved value. * @example * - * var object = { - * 'user': 'fred', - * 'age': function() { - * return 40; - * } - * }; + * var object = { 'user': 'fred', 'age': _.constant(40) }; * * _.result(object, 'user'); * // => 'fred' @@ -10071,13 +10065,16 @@ * * _.result(object, 'status', 'busy'); * // => 'busy' + * + * _.result(object, 'status', _.constant('busy')); + * // => 'busy' */ function result(object, key, defaultValue) { var value = object == null ? undefined : object[key]; if (typeof value == 'undefined') { - return defaultValue; + value = defaultValue; } - return isFunction(value) ? object[key]() : value; + return isFunction(value) ? value.call(object) : value; } /** diff --git a/test/test.js b/test/test.js index e2205d913..e844b6f29 100644 --- a/test/test.js +++ b/test/test.js @@ -10374,7 +10374,7 @@ }); 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) { result.push(value, value); @@ -10389,6 +10389,11 @@ deepEqual(actual, expected); }); + + test('should execute default function values', 1, function() { + var actual = _.result(object, 'd', object.c); + strictEqual(actual, 1); + }); }()); /*--------------------------------------------------------------------------*/