Skip to content

Commit 9705e86

Browse files
committed
Implements matches with tests #12
1 parent 364aef2 commit 9705e86

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/underscore.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1276,6 +1276,24 @@ def property(self):
12761276
"""
12771277
return self._wrap(lambda obj, *args: obj[self.obj])
12781278

1279+
def matches(self):
1280+
"""
1281+
Returns a predicate for checking whether an object has a given
1282+
set of `key:value` pairs.
1283+
"""
1284+
def ret(obj, *args):
1285+
if self.obj is obj:
1286+
return True # avoid comparing an object to itself.
1287+
1288+
for key in self.obj:
1289+
if self.obj[key] != obj[key]:
1290+
return False
1291+
1292+
return True
1293+
1294+
return self._wrap(ret)
1295+
1296+
12791297
def times(self, func, *args):
12801298
""" Run a function **n** times.
12811299
"""

tests/test_objects.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,13 @@ def test_invert(self):
132132
self.assertEqual(set(r), set('Larry Moe Curly'), 'can invert an object')
133133
self.assertEqual(_.invert(_.invert(obj)), obj, "two inverts gets you back where you started")
134134

135+
def test_matches(self):
136+
moe = {"name": 'Moe Howard', "hair": True};
137+
curly = {"name": 'Curly Howard', "hair": False};
138+
stooges = [moe, curly]
139+
self.assertTrue(_.find(stooges, _.matches({"hair": False})) == curly, "returns a predicate that can be used by finding functions.")
140+
self.assertTrue(_.find(stooges, _.matches(moe)) == moe, "can be used to locate an object exists in a collection.")
141+
135142
if __name__ == "__main__":
136143
print ("run these tests by executing `python -m unittest discover` in unittests folder")
137144
unittest.main()

0 commit comments

Comments
 (0)