Skip to content

Commit bf60c09

Browse files
committed
added collection utils
1 parent f86033f commit bf60c09

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

collection_utils.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# -*- coding: utf-8 -*-
2+
3+
import unittest
4+
5+
6+
def where(entries, properties):
7+
ret = []
8+
9+
if type(properties) is str:
10+
for entry in entries:
11+
if properties in entry:
12+
ret.append(entry[properties])
13+
14+
if type(properties) is list:
15+
for entry in entries:
16+
obj = {}
17+
for p in properties:
18+
if p in entry:
19+
obj[p] = entry[p]
20+
21+
ret.append(obj)
22+
23+
return ret
24+
25+
def initial(array):
26+
return array[0:len(array) - 1]
27+
28+
def rest(array):
29+
return array[1:len(array)]
30+
31+
32+
class FilterModule(object):
33+
""" utility filters for operating on hashes """
34+
35+
def filters(self):
36+
return {
37+
'where': where,
38+
'initial': initial,
39+
'rest': rest
40+
}
41+
42+
43+
class TestCollectionUtils(unittest.TestCase):
44+
def test_where(self):
45+
l = [
46+
{'foo': 'bar', 'bar': 'quuux', 'baz': 'qux'},
47+
{'foo': 'baz', 'bar': 'quuuux', 'baz': 'quux'}
48+
]
49+
self.assertEqual(where(l, 'foo'), ['bar', 'baz'])
50+
self.assertEqual(where(l, ['foo', 'baz']), [
51+
{'foo': 'bar', 'baz': 'qux'},
52+
{'foo': 'baz', 'baz': 'quux'}
53+
])
54+
55+
def test_initial(self):
56+
self.assertEqual(initial([1, 2, 3]), [1, 2])
57+
58+
def test_rest(self):
59+
self.assertEqual(rest([1, 2, 3]), [2, 3])
60+
61+
62+
if __name__ == '__main__':
63+
unittest.main()

0 commit comments

Comments
 (0)