JS transducers
/** Implementing transformations (like map and filter) with reducers. **/ | |
// https://www.webpackbin.com/bins/-Kvmn0gWkIMmtnFnkcu_ | |
// https://medium.com/@roman01la/understanding-transducers-in-javascript-3500d3bd9624 | |
// take all evens, multiply by 2, log that. | |
const arr = ['1', '2', '3', '4', '5', '6'] | |
console.log('Chaining map and filter.') | |
const arred = arr.filter((elem, index) => { | |
return parseInt(elem) % 2 === 0 | |
}).map(elem => { | |
return elem * 2; | |
}) | |
arred.forEach(console.log, console) // 4 8 12 | |
console.log('Implement map with reduce.') | |
const mapReducerOld = (result, input) => { | |
result.push(input * 2) | |
return result | |
} | |
const mapped = arr.reduce(mapReducerOld, []) | |
mapped.forEach(console.log, console) | |
// 2 4 6 8 10 12 | |
console.log('Same stuff, but passing in mapping function from outside.') | |
const mapReducer = (f) => (result, input) => { | |
result.push(f(input)) | |
return result | |
} | |
// code above is the ES6 equivalent to: | |
const mapReducerNoES6 = function(f) { | |
return function(result, input) { | |
result.push(f(input)) | |
return result | |
} | |
} | |
const mappedIt = arr.reduce(mapReducer((f) => f * 2), []) | |
mappedIt.forEach(console.log, console) | |
// 2 4 6 8 10 12 | |
console.log('With this new syntax, we can filter too!') | |
const filterReducer = (predicate) => (result, input) => { | |
if (predicate(input)) { | |
result.push(input) | |
} | |
return result | |
} | |
const filteredIt = arr.reduce(filterReducer((x) => x <= 4), []) | |
filteredIt.forEach(console.log, console) | |
// "1" "2" "3" "4" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment