[Functional Programming] Function modelling -- 6. contramap

Normally when we use 'map', we do the transform base on the output. 'contramap' can do the transform base on the input, which means, before the orginal input passed to the function, we apply 'contramap' to modify the input arguements.

 

Example for 'contramap':

const Reducer = run => ({
  run,
  contraMap(f) {
    return Reducer((acc, x) => run(acc, f(x))); // For the reducer, we cannot change 'acc', but we can modify 'curr'
  }
});

 Reducer(login).contraMap(payload => payload.user)
   .concat(Reducer(changePage).contraMap(payload => payload.currentPage))
   .run(state, {user: {}, currentPage: {}})

 

More examples checkout the previous post.

posted @ 2020-03-15 21:11  Zhentiw  阅读(156)  评论(0编辑  收藏  举报