Permalink
Browse files

Added compact()

  • Loading branch information...
1 parent 8bd304d commit b45410ab33595cbca1da1bd8c158290fe11db441 @Suor committed Feb 27, 2013
Showing with 28 additions and 2 deletions.
  1. +3 −0 CHANGELOG
  2. +1 −0 README.rst
  3. +9 −0 docs/colls.rst
  4. +1 −1 from_underscore.txt
  5. +10 −1 funcy/colls.py
  6. +4 −0 tests/test_colls.py
View
@@ -1,3 +1,6 @@
+0.3.3
+- added compact()
+
0.3.2
- added ilen()
- added some object helpers: namespace base class and @cached_property
View
@@ -43,6 +43,7 @@ Select a part of collection::
select(even, {1,2,3,10,20}) # {2,10,20}
select(re_tester('^a'), ('a','b','ab','ba')) # ('a','ab')
select_keys(callable, {str: '', None: None}) # {str: ''}
+ compact({2, None, '', 0}) # {2,'',0}
Test collection contents::
View
@@ -101,6 +101,15 @@ Transform and select
select_values(bool, some_dict)
+.. function:: compact(pred, coll)
+
+ Removes ``None`` values from given collection. When compacting a dict all keys with ``None`` values are trashed.
+
+ Extract integer data from request::
+
+ compact(walk_values(silent(int), request_dict))
+
+
Dict utils
----------
View
@@ -3,7 +3,7 @@ countby
foldl?=reduce foldr?
# Array
-compact=keep/1? without(relates to conj)
+without(relates to conj)
flatten?
# Functions
View
@@ -8,7 +8,7 @@
__all__ = ['empty', 'iteritems', 'join', 'merge',
- 'walk', 'walk_keys', 'walk_values', 'select', 'select_keys', 'select_values',
+ 'walk', 'walk_keys', 'walk_values', 'select', 'select_keys', 'select_values', 'compact',
'is_distinct', 'all', 'any', 'none', 'one', 'some',
'zipdict', 'flip', 'project',
'where', 'pluck', 'invoke']
@@ -90,6 +90,15 @@ def select_keys(pred, coll):
def select_values(pred, coll):
return select(lambda (k, v): pred(v), coll)
+
+def compact(coll):
+ pred = lambda x: x is not None
+ if isinstance(coll, Mapping):
+ return select_values(pred, coll)
+ else:
+ return select(pred, coll)
+
+
### Content tests
def is_distinct(coll):
View
@@ -88,6 +88,10 @@ def test_select_keys():
def test_select_values():
assert select_values(_ % 2, {'a': 1, 'b': 2}) == {'a': 1}
+def test_compact():
+ assert eq(compact([0, 1, None, 3]), [0, 1, 3])
+ assert eq(compact((0, 1, None, 3)), (0, 1, 3))
+ assert eq(compact({'a': None, 'b': 0, 'c': 1}), {'b': 0, 'c': 1})
def test_is_distinct():
assert is_distinct('abc')

0 comments on commit b45410a

Please sign in to comment.