mirror of
https://github.com/whoisclebs/lodash.git
synced 2026-02-02 16:17:50 +00:00
Make _.result resolve values of functions as it deep crawls over them.
This commit is contained in:
25
lodash.js
25
lodash.js
@@ -12282,17 +12282,24 @@
|
||||
* // => 'default'
|
||||
*/
|
||||
function result(object, path, defaultValue) {
|
||||
if (!isKey(path, object)) {
|
||||
path = baseCastPath(path);
|
||||
var result = baseGet(object, path);
|
||||
object = parent(object, path);
|
||||
} else {
|
||||
result = object == null ? undefined : object[path];
|
||||
path = isKey(path, object) ? [path] : baseCastPath(path);
|
||||
|
||||
var index = -1,
|
||||
length = path.length;
|
||||
|
||||
if (!length) {
|
||||
object = undefined;
|
||||
length = 1;
|
||||
}
|
||||
if (result === undefined) {
|
||||
result = defaultValue;
|
||||
while (++index < length) {
|
||||
var value = object == null ? undefined : object[path[index]];
|
||||
if (value === undefined) {
|
||||
index = length;
|
||||
value = defaultValue;
|
||||
}
|
||||
object = value = isFunction(value) ? value.call(object) : value;
|
||||
}
|
||||
return isFunction(result) ? result.call(object) : result;
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
27
test/test.js
27
test/test.js
@@ -18301,28 +18301,15 @@
|
||||
});
|
||||
|
||||
QUnit.test('`_.' + methodName + '` should follow `path` over non-plain objects', function(assert) {
|
||||
assert.expect(4);
|
||||
assert.expect(2);
|
||||
|
||||
var object = { 'a': '' },
|
||||
paths = ['constructor.prototype.a', ['constructor', 'prototype', 'a']];
|
||||
var paths = ['a.b.c', ['a', 'b', 'c']];
|
||||
|
||||
lodashStable.each(paths, function(path) {
|
||||
numberProto.a = 1;
|
||||
|
||||
var actual = func(0, path);
|
||||
assert.strictEqual(actual, 1);
|
||||
|
||||
numberProto.a = { 'b': { 'c': 1 } };
|
||||
assert.strictEqual(func(0, path), 1);
|
||||
delete numberProto.a;
|
||||
});
|
||||
|
||||
lodashStable.each(['a.replace.b', ['a', 'replace', 'b']], function(path) {
|
||||
stringProto.replace.b = 1;
|
||||
|
||||
var actual = func(object, path);
|
||||
assert.strictEqual(actual, 1);
|
||||
|
||||
delete stringProto.replace.b;
|
||||
});
|
||||
});
|
||||
|
||||
QUnit.test('`_.' + methodName + '` should return the default value for `undefined` values', function(assert) {
|
||||
@@ -18346,6 +18333,12 @@
|
||||
|
||||
assert.deepEqual(actual, expected);
|
||||
});
|
||||
|
||||
QUnit.test('`_.' + methodName + '` should return the default value when `path` is empty', function(assert) {
|
||||
assert.expect(1);
|
||||
|
||||
assert.strictEqual(func({}, [], 'a'), 'a');
|
||||
});
|
||||
});
|
||||
|
||||
/*--------------------------------------------------------------------------*/
|
||||
|
||||
Reference in New Issue
Block a user