Skip to content

Commit 02ba01b

Browse files
author
Nik Krimm
committed
[jashkenas#2286]: Underscore could use a _.propertyResult
1 parent 53086b0 commit 02ba01b

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

test/utility.js

+12
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, 'passes rest of arguments to named method for evaluation');
102+
assert.equal(_.method(function () { return this.name(); })(stooge), 'moe', 'attempts to apply a function literal passed.');
103+
assert.equal(_.method(function (a,b,c) { return this.sum(a,b,c); })(stooge, 1, 2, 3), 6, 'passes 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

+18
Original file line numberDiff line numberDiff line change
@@ -1370,6 +1370,24 @@
13701370

13711371
_.property = property;
13721372

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

0 commit comments

Comments
 (0)