Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ R.propEq(1, 'v1', {'v1': 1}) # True
- [x] reduce
- [x] reduceBy
- [x] reduced
- [ ] reduceRight
- [x] reduceRight
- [ ] reduceWhile
- [x] reject
- [ ] remove
Expand Down
1 change: 1 addition & 0 deletions ramda/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions ramda/reduceRight.py
Original file line number Diff line number Diff line change
@@ -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)
35 changes: 35 additions & 0 deletions test/test_reduceRight.py
Original file line number Diff line number Diff line change
@@ -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()