Last active
September 27, 2017 18:44
-
-
Save federicofazzeri/600db3919f2ab1ceec9cb3121270565b to your computer and use it in GitHub Desktop.
List transformations chaining maps can be optimized with a transducer, here an example in plain Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var test = require('tape'); | |
const double = n => n*2; | |
const addOne = n => n+1; | |
const excludeTen = n => n !== 10; | |
const listPush = (list, v) => { | |
list.push(v); | |
return list; | |
} | |
const mapReducer = mapFn => | |
listHandler => | |
(acc, v) => listHandler( acc, mapFn(v) ) | |
const filterReducer = filterFn => | |
listHandler => | |
(acc, v) => ( filterFn(v) ) ? listHandler( acc, v ) : acc; | |
const pipeFns = (...fns) => | |
fns.reduce( (fnAcc, fnNext) => | |
v => fnAcc( fnNext( v ) ) | |
) | |
const arr = [1,2,3,4]; | |
const expected = [6,14,18]; | |
console.log('should create the transformed array:'); | |
test('mapping the list with each transformation function', function (t) { | |
const res = arr | |
.map(double) | |
.map(addOne) | |
.map(double) | |
.filter(excludeTen) | |
t.equal( res.toString(), expected.toString() ); | |
t.end() | |
}); | |
test('reducing the list with each transformation function', function (t) { | |
const res = arr | |
.reduce( mapReducer( double )(listPush), [] ) | |
.reduce( mapReducer( addOne )(listPush), [] ) | |
.reduce( mapReducer( double )(listPush), [] ) | |
.reduce( filterReducer( excludeTen )(listPush), [] ) | |
t.equal(res.toString(),expected.toString()); | |
t.end() | |
}); | |
test('reducing the list using a transducer', function (t) { | |
const transducer = pipeFns( | |
mapReducer( double ), | |
mapReducer( addOne ), | |
mapReducer( double ), | |
filterReducer( excludeTen ) | |
) | |
const res = arr | |
.reduce( transducer(listPush) , [] ) | |
t.equal(res.toString(),expected.toString()); | |
t.end() | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment