diff --git a/README.md b/README.md index e0cdc36..5caf0b2 100644 --- a/README.md +++ b/README.md @@ -410,7 +410,7 @@ R.propEq(1, 'v1', {'v1': 1}) # True - [x] reduce - [x] reduceBy - [x] reduced -- [ ] reduceRight +- [x] reduceRight - [ ] reduceWhile - [x] reject - [ ] remove diff --git a/ramda/__init__.py b/ramda/__init__.py index 3d6647a..3c7c37b 100644 --- a/ramda/__init__.py +++ b/ramda/__init__.py @@ -67,6 +67,7 @@ from .reduce import reduce from .reduceBy import reduceBy from .reduced import reduced +from .reduceRight import reduceRight from .reject import reject from .reverse import reverse from .slice import slice diff --git a/ramda/reduceRight.py b/ramda/reduceRight.py new file mode 100644 index 0000000..2b3a4c3 --- /dev/null +++ b/ramda/reduceRight.py @@ -0,0 +1,16 @@ +from .private._curry3 import _curry3 +from .private._helper import getAttribute + + +def inner_reduceRight(fn, acc, arr): + idx = len(arr) - 1 + while idx >= 0: + acc = fn(arr[idx], acc) + if acc and getAttribute(acc, '@@transducer/reduced'): + acc = getAttribute(acc, '@@transducer/value') + break + idx -= 1 + return acc + + +reduceRight = _curry3(inner_reduceRight) diff --git a/test/test_reduceRight.py b/test/test_reduceRight.py new file mode 100644 index 0000000..2548fa8 --- /dev/null +++ b/test/test_reduceRight.py @@ -0,0 +1,35 @@ + +import unittest + +import ramda as R + +""" +https://github.com/ramda/ramda/blob/master/test/reduceRight.js +""" + + +def avg(a, b): return (a + b) / 2 + + +def concatFirstThree(val, acc): return R.reduced(acc) if len(acc) == 3 else R.concat(acc, val) + + +class TestReduceRight(unittest.TestCase): + def test_folds_lists_in_the_right_order(self): + self.assertEqual('abcd', R.reduceRight(lambda a, b: a + b, '', ['a', 'b', 'c', 'd'])) + + def test_folds_subtract_over_arrays_in_the_right_order(self): + self.assertEqual(-2, R.reduceRight(lambda a, b: a - b, 0, [1, 2, 3, 4])) + + def test_folds_simple_functions_over_arrays_with_the_supplied_accumulator(self): + self.assertEqual(12, R.reduceRight(avg, 54, [12, 4, 10, 6])) + + def test_returns_the_accumulator_for_an_empty_array(self): + self.assertEqual(0, R.reduceRight(avg, 0, [])) + + def test_short_circuits_with_reduced(self): + self.assertEqual('ram', R.reduceRight(concatFirstThree, '', ['a', 'd', 'm', 'a', 'r'])) + + +if __name__ == '__main__': + unittest.main()