diff --git a/README.md b/README.md index cf1682e..8e2bf96 100644 --- a/README.md +++ b/README.md @@ -582,7 +582,7 @@ R.pick(['v1'], obj) # {'v1': 1} R.pickAll(['v1', 'v3'], obj) # {'v1': 1, 'v3': None} ``` -- [ ] pickBy +- [x] pickBy - [x] 0.1.2 pipe - [ ] pipeWith - [x] 0.1.2 pluck diff --git a/ramda/__init__.py b/ramda/__init__.py index c6c4a8f..41bd664 100644 --- a/ramda/__init__.py +++ b/ramda/__init__.py @@ -97,6 +97,7 @@ from .paths import paths from .pick import pick from .pickAll import pickAll +from .pickBy import pickBy from .pipe import pipe from .pluck import pluck from .prepend import prepend diff --git a/ramda/pickBy.py b/ramda/pickBy.py new file mode 100644 index 0000000..13a656c --- /dev/null +++ b/ramda/pickBy.py @@ -0,0 +1,20 @@ +from .private._curry2 import _curry2 +from .private._inspect import funcArgsLength + + +def inner_pickBy(test, obj): + result = {} + for key in obj: + if funcArgsLength(test) <= 1: + if test(obj[key]): + result[key] = obj[key] + if funcArgsLength(test) == 2: + if test(obj[key], key): + result[key] = obj[key] + if funcArgsLength(test) == 3: + if test(obj[key], key, obj): + result[key] = obj[key] + return result + + +pickBy = _curry2(inner_pickBy) diff --git a/test/test_pickBy.py b/test/test_pickBy.py new file mode 100644 index 0000000..207a16b --- /dev/null +++ b/test/test_pickBy.py @@ -0,0 +1,40 @@ +import unittest + +import ramda as R + +""" +https://github.com/ramda/ramda/blob/master/test/pickBy.js +""" + +obj = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6} + + +class TestPickBy(unittest.TestCase): + def test_create_a_copy_of_the_object(self): + self.assertEqual(obj, R.pickBy(R.always(True), obj)) + + def test_when_returning_truth_keeps_the_key(self): + self.assertEqual(obj, R.pickBy(R.T, obj)) + self.assertEqual(obj, R.pickBy(R.always({'a': 1}), obj)) + self.assertEqual(obj, R.pickBy(R.always(1), obj)) + + def test_when_returning_falsy_do_not_keep_the_key(self): + self.assertEqual({}, R.pickBy(R.F, obj)) + self.assertEqual({}, R.pickBy(R.always({}), obj)) + self.assertEqual({}, R.pickBy(R.always(0), obj)) + self.assertEqual({}, R.pickBy(R.always(None), obj)) + + def test_is_called_with_val_key_obj(self): + def pred(val, key, _obj): + self.assertEqual(obj, _obj) + return key == 'd' and val == 4 + self.assertEqual({'d': 4}, R.pickBy(pred, obj)) + + def test_first_method_has_2_param(self): + def pred(val, key): + return key == 'd' and val == 4 + self.assertEqual({'d': 4}, R.pickBy(pred, obj)) + + +if __name__ == '__main__': + unittest.main()