Sunday, December 3, 2017

Transducing in JS

Say there is a list

var list = [3,4,7,8,11,14,15]

And we want to apply following function to each element

function add1 (n) { return n+1;}

And then filter out only the odd numbers

function isOdd (n) { return n%%2=1;}

And then get sum of those numbers

function sum (total, n) { return total +n };


This can be done :

list
.map(add1)
.filter(isOdd)
.reduce(sum);

This can be reduced to a one line code by using transducer which takes up a sum function as combiner.

Transducer will compose mapReducer and filterReducer together.



Further Reading

frontendmasters.com
Full code - https://gist.github.com/getify/7ba2b8f5a50116f3efa2849e4c6d1f79
http://jlongster.com/Transducers.js--A-JavaScript-Library-for-Transformation-of-Data




No comments:

Post a Comment