Skip to content

Instantly share code, notes, and snippets.

@getify
Last active February 28, 2022 16:38
Show Gist options
  • Save getify/7ba2b8f5a50116f3efa2849e4c6d1f79 to your computer and use it in GitHub Desktop.
Save getify/7ba2b8f5a50116f3efa2849e4c6d1f79 to your computer and use it in GitHub Desktop.
transducing in javascript
function add1(v) { return v + 1; }
function isOdd(v) { return v % 2 == 1; }
function sum(total,v) { return total + v; }
var list = [2,5,8,11,14,17,20];
list
.map( add1 )
.filter( isOdd )
.reduce( sum );
// 48
function add1(v) { return v + 1; }
function isOdd(v) { return v % 2 == 1; }
function sum(total,v) { return total + v; }
function listReduction(list,v) {
list.push(v);
return list;
}
function mapReducer(mapperFn) {
return function(reductionFn){
return function(list,v){
return reductionFn( list, mapperFn(v) );
};
};
}
function filterReducer(predicateFn) {
return function(reductionFn){
return function(list,v){
if (predicateFn(v)) return reductionFn( list, v );
return list;
};
};
}
var list = [2,5,8,11,14,17,20];
list
.reduce( mapReducer(add1)(listReduction), [] )
.reduce( filterReducer(isOdd)(listReduction), [] )
.reduce( sum );
// 48
function add1(v) { return v + 1; }
function isOdd(v) { return v % 2 == 1; }
function sum(total,v) { return total + v; }
function composeRight(fn1,fn2) {
return function(...args){
return fn1(fn2(...args));
};
}
function listReduction(list,v) {
list.push(v);
return list;
}
function mapReducer(mapperFn) {
return function(reductionFn){
return function(list,v){
return reductionFn( list, mapperFn(v) );
};
};
}
function filterReducer(predicateFn) {
return function(reductionFn){
return function(list,v){
if (predicateFn(v)) return reductionFn( list, v );
return list;
};
};
}
var transducer =
composeRight( mapReducer(add1), filterReducer(isOdd) )( listReduction );
var list = [2,5,8,11,14,17,20];
list
.reduce( transducer, [] )
.reduce( sum );
// 48
function add1(v) { return v + 1; }
function isOdd(v) { return v % 2 == 1; }
function sum(total,v) { return total + v; }
function composeRight(fn1,fn2) {
return function(...args){
return fn1(fn2(...args));
};
}
function mapReducer(mapperFn) {
return function(reductionFn){
return function(list,v){
return reductionFn( list, mapperFn(v) );
};
};
}
function filterReducer(predicateFn) {
return function(reductionFn){
return function(list,v){
if (predicateFn(v)) return reductionFn( list, v );
return list;
};
};
}
var transducer =
composeRight( mapReducer(add1), filterReducer(isOdd) )( sum );
var list = [2,5,8,11,14,17,20];
list
.reduce( transducer, 0 )
// 48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment