Skip to content

Commit 3fa1ae3

Browse files
author
Nik Krimm
committed
Add _.method as peer to _.property for capturing return values of functions on an Object. Closes #2286: Underscore could use a _.propertyResult.
1 parent 53086b0 commit 3fa1ae3

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

test/utility.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,18 @@
9595
assert.equal(undefPropertyOf('curly'), void 0, 'should return undefined when obj is undefined');
9696
});
9797

98+
QUnit.test('method', function(assert) {
99+
var stooge = {name: function() { return 'moe'; }, sum: function(a, b, c) { return a + b + c; }};
100+
assert.equal(_.method('name')(stooge), 'moe', 'should return the results of calling the method with the given name');
101+
assert.equal(_.method('sum')(stooge, 1, 2, 3), 6, 'should pass rest of arguments to named method for evaluation');
102+
assert.equal(_.method(function() { return this.name(); })(stooge), 'moe', 'should apply a function literal passed.');
103+
assert.equal(_.method(function(a, b, c) { return this.sum(a, b, c); })(stooge, 1, 2, 3), 6, 'should pass arguments when applying a function literal.');
104+
assert.equal(_.method('macerena')(stooge), void 0, 'should return undefined for non-existant method name on defined object');
105+
assert.equal(_.method('name')(null), void 0, 'should return undefined for null object');
106+
assert.equal(_.method()(stooge), void 0, 'should return undefined for undefined method name on existing object');
107+
assert.equal(_.method()(void 0), void 0, 'should return undefined for undefined method name on undefined object');
108+
});
109+
98110
QUnit.test('random', function(assert) {
99111
var array = _.range(1000);
100112
var min = Math.pow(2, 31);

underscore.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1370,6 +1370,21 @@
13701370

13711371
_.property = property;
13721372

1373+
// Generates a function for a given object that returns the passed function's return value.
1374+
// Accepts a method name or function literal for value.
1375+
// If value is a string, function assumes this string is a method name on the
1376+
// referenced object.
1377+
_.method = function(value) {
1378+
return restArgs(function(obj, args) {
1379+
if (obj == null) { return; }
1380+
var func = _.isFunction(value) ? value : obj[value];
1381+
if (func) {
1382+
return func.apply(obj, args);
1383+
}
1384+
});
1385+
};
1386+
1387+
13731388
// Generates a function for a given object that returns a given property.
13741389
_.propertyOf = function(obj) {
13751390
return obj == null ? function(){} : function(key) {

0 commit comments

Comments
 (0)