I’m trying to understand Ramda’s transducers. Here’s a slightly modified example from the docs:
JavaScript
x
5
1
const numbers = [1, 2, 3, 4];
2
const isOdd = (x) => x % 2 === 1;
3
const firstFiveOddTransducer = R.compose(R.filter(isOdd), R.take(5));
4
R.transduce(firstFiveOddTransducer, R.flip(R.append), [], R.range(0, 100)); //=> [ 1, 3, 5, 7, 9 ]
5
But what if I want to sum the elements of the resulting array? The following (just adding R.sum
into R.compose
) doesn’t work:
JavaScript
1
2
1
const firstFiveOddTransducer = R.compose(R.filter(isOdd), R.take(5), R.sum);
2
Advertisement
Answer
I’d do something like this, just accumulate on top of an initial 0 value
JavaScript
1
11
11
1
const list = [1, 2, 3, 4, 5];
2
const isOdd = R.filter(n => n % 2);
3
4
const transducer = R.compose(isOdd);
5
6
const result = R.transduce(transducer, R.add, 0, list);
7
8
console.log(
9
'result',
10
result,
11
);
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>