[Functional Programming ADT] Create State ADT Based Reducers (applyTo, Maybe)

The typical Redux Reducer is function that takes in the previous state and an action and uses a switch case to determine how to transition the provided State. We can take advantage of the Action Names being Strings and replace the typical switch case with a JavaScript Object that pairs our State ADT reducers with their actions.

We can also take care of the case in which a reducer does not have an implementation for a given action, by reaching for the Maybe data type and updating our main Redux reducer to handle the case for us, by providing the previous state untouched. And all of this can be captured in a simple helper function we can use in all of our reducer files.

 

This post will focus on how to do reducer pattern, not the functionalities details, all the functionalities codes are listed here:

const {prop, isSameType, State, when, assign, omit, curry, converge,map, composeK, liftA2, equals, constant,option, chain, mapProps, find, propEq, isNumber, compose, safe} = require('crocks');
const  {get, modify, of} = State; 

const state = {
    cards: [
        {id: 'green-square', color: 'green', shape: 'square'},
        {id: 'orange-square', color: 'orange', shape: 'square'},
        {id: 'blue-triangle', color: 'blue', shape: 'triangle'}
    ],
    hint: {
        color: 'green',
        shape: 'square'
    },
    isCorrect: null,
    rank: 4,
    left: 8,
    moves: 0
}
const inc = x => x + 1;
const dec = x => x - 1;
const incOrDec = b => b ? dec :  inc;
const clamp = (min, max) => x => Math.min(Math.max(min, x), max);
const clampAfter = curry((min, max, fn) => compose(clamp(min, max), fn))
const limitRank = clampAfter(0, 4);
const over = (key, fn) => modify(mapProps({[key]: fn}))
const getState = key => get(prop(key));
const liftState = fn => compose(
    of,
    fn
)
const limitMoves = clampAfter(0, 8);
const decLeft = () => over("left", limitMoves(dec));
const incMoves = () => over("moves", limitMoves(inc));
const assignBy = (pred, obj) =>
  when(pred, assign(obj));
const applyMove =
  composeK(decLeft, incMoves)

const getCard = id => getState('cards')
    .map(chain(find(propEq('id', id))))
    .map(option({}))
const getHint = () => getState('hint')
    .map(option({}))
const cardToHint = composeK(
    liftState(omit(['id'])),
    getCard
)
const validateAnswer = converge(
    liftA2(equals),
    cardToHint,
    getHint
)
const setIsCorrect = b => over('isCorrect', constant(b));
const adjustRank = compose(limitRank, incOrDec);
const updateRank = b => over('rank', adjustRank(b));
const applyFeedback = converge(
    liftA2(constant),
    setIsCorrect,
    updateRank
)
const markSelected = id =>
  assignBy(propEq('id', id), { selected: true })
const selectCard = id =>
  over('cards', map(markSelected(id)))
const answer = composeK(
    applyMove,
    selectCard
) 
const feedback = composeK(
    applyFeedback,
    validateAnswer
)
View Code

 

For now, the reducer pattern was implemented like this:

// Action a :: {type: string, payload: a}
// createAction :: String -> a -> Action a
const createAction = type => payload => ({type, payload});
const SELECT_CARD = 'SELECT_CARD';
const SHOW_FEEDBACK = 'SHOW_FEEDBACK';
const selectCardAction = createAction(SELECT_CARD);
const showFeedbackAction = createAction(SHOW_FEEDBACK);

// reducer :: (State, a) -> (State AppState ()) | Null
const reducer = (prevState, {type, payload}) => {
    let result;
    switch(type) {
        case SELECT_CARD:
            result = answer(payload);
            break;
        case SHOW_FEEDBACK:
            result = feedback(payload);
            break;            
        default: 
            result = null;   
    }

    return isSameType(State, result) ? result.execWith(prevState): prevState;
}

console.log(
    reducer(
        state,
        showFeedbackAction('green-square')
    )
)

 

Instead of using 'Switch', we can use Object to do the reducer:

const actionReducer= {
    SELECT_CARD: answer,
    SHOW_FEEDBACK: feedback
}

const turn = ({type, payload}) => (actionReducer[type] || Function.prototype)(payload);

const reducer = (prevState, action) => {
    const result = turn(action);
    return isSameType(State, result) ? result.execWith(prevState) : prevState;
}

'Function.prototype' makes sure that it always return a function can accept payload as param, just it do nothing and return undefined.

 

And code:

(actionReducer[type] || Function.prototype)

it is prefect for Maybe type, so we can continue with refactoring with Maybe:

const createReducer = actionReducer => ({type, payload}) => 
    prop(type, actionReducer)  // safe check type exists on actionReducer
        .map(applyTo(payload)) // we get back a function need to call with payload, using applyTo 
const turn = createReducer({
    SELECT_CARD: answer,
    SHOW_FEEDBACK: feedback
}) 
const reducer = (prevState, action) => {
    return turn(action)
        .chain(safe(isSameType(State))) // check result is the same type as State
        .map(execWith(prevState))       // run with execWith
        .option(prevState);             // unwrap Just and provide default value
    
};

 

---

 

  1 const {prop, execWith, applyTo, isSameType, State, when, assign, omit, curry, converge,map, composeK, liftA2, equals, constant,option, chain, mapProps, find, propEq, isNumber, compose, safe} = require('crocks');
  2 const  {get, modify, of} = State; 
  3 
  4 const state = {
  5     cards: [
  6         {id: 'green-square', color: 'green', shape: 'square'},
  7         {id: 'orange-square', color: 'orange', shape: 'square'},
  8         {id: 'blue-triangle', color: 'blue', shape: 'triangle'}
  9     ],
 10     hint: {
 11         color: 'green',
 12         shape: 'square'
 13     },
 14     isCorrect: null,
 15     rank: 4,
 16     left: 8,
 17     moves: 0
 18 }
 19 const inc = x => x + 1;
 20 const dec = x => x - 1;
 21 const incOrDec = b => b ? dec :  inc;
 22 const clamp = (min, max) => x => Math.min(Math.max(min, x), max);
 23 const clampAfter = curry((min, max, fn) => compose(clamp(min, max), fn))
 24 const limitRank = clampAfter(0, 4);
 25 const over = (key, fn) => modify(mapProps({[key]: fn}))
 26 const getState = key => get(prop(key));
 27 const liftState = fn => compose(
 28     of,
 29     fn
 30 )
 31 const limitMoves = clampAfter(0, 8);
 32 const decLeft = () => over("left", limitMoves(dec));
 33 const incMoves = () => over("moves", limitMoves(inc));
 34 const assignBy = (pred, obj) =>
 35   when(pred, assign(obj));
 36 const applyMove =
 37   composeK(decLeft, incMoves)
 38 
 39 const getCard = id => getState('cards')
 40     .map(chain(find(propEq('id', id))))
 41     .map(option({}))
 42 const getHint = () => getState('hint')
 43     .map(option({}))
 44 const cardToHint = composeK(
 45     liftState(omit(['id'])),
 46     getCard
 47 )
 48 const validateAnswer = converge(
 49     liftA2(equals),
 50     cardToHint,
 51     getHint
 52 )
 53 const setIsCorrect = b => over('isCorrect', constant(b));
 54 const adjustRank = compose(limitRank, incOrDec);
 55 const updateRank = b => over('rank', adjustRank(b));
 56 const applyFeedback = converge(
 57     liftA2(constant),
 58     setIsCorrect,
 59     updateRank
 60 )
 61 const markSelected = id =>
 62   assignBy(propEq('id', id), { selected: true })
 63 const selectCard = id =>
 64   over('cards', map(markSelected(id)))
 65 const answer = composeK(
 66     applyMove,
 67     selectCard
 68 ) 
 69 const feedback = composeK(
 70     applyFeedback,
 71     validateAnswer
 72 )
 73 // Action a :: {type: string, payload: a}
 74 // createAction :: String -> a -> Action a
 75 const createAction = type => payload => ({type, payload});
 76 const SELECT_CARD = 'SELECT_CARD';
 77 const SHOW_FEEDBACK = 'SHOW_FEEDBACK';
 78 const selectCardAction = createAction(SELECT_CARD);
 79 const showFeedbackAction = createAction(SHOW_FEEDBACK);
 80 
 81 const createReducer = actionReducer => ({type, payload}) => 
 82     prop(type, actionReducer)  // safe check type exists on actionReducer
 83         .map(applyTo(payload)) // we get back a function need to call with payload, using applyTo 
 84 const turn = createReducer({
 85     SELECT_CARD: answer,
 86     SHOW_FEEDBACK: feedback
 87 }) 
 88 
 89 const reducer = (prevState, action) => {
 90     return turn(action)
 91         .chain(safe(isSameType(State))) // check result is the same type as State
 92         .map(execWith(prevState))       // run with execWith
 93         .option(prevState);             // unwrap Just and provide default value
 94     
 95 };
 96 
 97 const sillyVerb = createAction('SILLY_VERB');
 98 
 99 console.log(
100     reducer(
101         state,
102         selectCardAction('green-square')
103     )
104 )

 

转载于:https://www.cnblogs.com/Answer1215/p/10353011.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值