Skip to content

Commit

Permalink
Added _.propertyOf method and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
bathos committed Nov 5, 2014
1 parent 3397cad commit 27e6d46
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
18 changes: 18 additions & 0 deletions test/utility.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,24 @@
equal(_.property('name')(null), undefined, 'should return undefined for null values');
equal(_.property('name')(undefined), undefined, 'should return undefined for undefined values');
});

test('propertyOf', function() {
var stoogeRanks = _.propertyOf({curly: 2, moe: 1, larry: 3});
equal(stoogeRanks('curly'), 2, 'should return the property with the given name');
equal(stoogeRanks(null), undefined, 'should return undefined for null values');
equal(stoogeRanks(undefined), undefined, 'should return undefined for undefined values');

function MoreStooges() { this.shemp = 87; }
MoreStooges.prototype = {curly: 2, moe: 1, larry: 3};
var moreStoogeRanks = _.propertyOf(new MoreStooges());
equal(moreStoogeRanks('curly'), 2, 'should return properties from further up the prototype chain');

var nullPropertyOf = _.propertyOf(null);
equal(nullPropertyOf('curly'), undefined, 'should return undefined when obj is null');

var undefPropertyOf = _.propertyOf(undefined);
equal(undefPropertyOf('curly'), undefined, 'should return undefined when obj is undefined');
});

test('random', function() {
var array = _.range(1000);
Expand Down
7 changes: 7 additions & 0 deletions underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -1215,6 +1215,13 @@
return obj == null ? void 0 : obj[key];
};
};

// Generates a function for a given object that returns a given property (including those of ancestors)
_.propertyOf = function(obj) {
return obj == null ? _.noop : function(key) {
return obj[key];
};
};

// Returns a predicate for checking whether an object has a given set of `key:value` pairs.
_.matches = function(attrs) {
Expand Down

0 comments on commit 27e6d46

Please sign in to comment.