Created
December 25, 2015 08:21
-
-
Save stoeffel/fdb9b62407fac9e53f02 to your computer and use it in GitHub Desktop.
This file contains 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
const even = R.converge(R.equals, [R.always(0), R.modulo(R.__,2)]); | |
const odd = R.converge(R.equals, [R.always(1), R.modulo(R.__,2)]); | |
// 1. map/filter implemented with reduce | |
// map with reduce | |
const map = (f, functor) => | |
R.reduce((acc, next) => R.concat(acc, f(next)), [], functor) | |
expect(map(R.inc, [1, 2, 3])).toEqual([2, 3, 4]); | |
console.log('#map passed') | |
// filter with reduce | |
const filter = (pred, functor) => | |
R.reduce((acc, next) => pred(next)? R.concat(acc, next): acc, [], functor) | |
expect(filter(even, [1, 2, 3, 4, 5])).toEqual([2, 4]); | |
console.log('#filter passed') | |
// 2. decouple map/filter from reduce | |
const mapper = (f, functor) => | |
(acc, next) => R.concat(acc, f(next)) | |
expect(R.reduce(mapper(R.inc), [], [1, 2, 3])).toEqual([2, 3, 4]); | |
console.log('#mapper passed') | |
const filterer = (pred, functor) => | |
(acc, next) => pred(next)? R.concat(acc, next): acc | |
expect(R.reduce(filterer(even), [], [1, 2, 3, 4, 5])).toEqual([2, 4]); | |
console.log('#filterer passed') | |
// 3. decouple map/filter from concat | |
const mapping = transform => step => (acc, next) => step(acc, transform(next)); | |
expect(R.reduce(mapping(R.inc)(R.concat), [], [1, 2, 3])).toEqual([2, 3, 4]); | |
console.log('#mapping passed') | |
const filtering = pred => step => (acc, next) => pred(next)? step(acc, next): acc; | |
expect(R.reduce(filtering(odd)(R.concat), [], [1, 2, 3])).toEqual([1, 3]); | |
console.log('#filtering passed') | |
const transformation = R.compose( mapping( R.multiply(3) ) | |
, filtering( odd ) | |
); | |
expect(R.reduce(transformation(R.concat), [], [1, 2, 3])).toEqual([3, 9]); | |
console.log('#compose passed') | |
expect(R.reduce(transformation((acc, next) => acc + next + ''), '', [1, 2, 3])).toEqual('39'); | |
console.log('#join passed') | |
const transduce = R.compose( R.reduce | |
, mapping( R.multiply(3) ) | |
, filtering( odd ) | |
); | |
expect(transduce(R.concat)([], [1, 2, 3])).toEqual([3, 9]); | |
console.log('#transduce passed') | |
// 4. add reduced (to stop transformation) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment