[Functional Programming ADT] Adapt Redux Actions/Reducers for Use with the State ADT
By using the State ADT to define how our application state transitions over time, we clear up the need for a some of the boilerplate that we typically need for a solid Redux integration. We can keep our action names and creators in the same file as the reducer they are used in, as we no longer need to have separate files to hand the same action across different portions of our state.
We will build our a single reducer that will handle the integration with Redux and organize our State ADT based reducers in their own files and bring them into our main reducer to handle running our state transitions and the cases where we do not have an transition for a given action.
// Action a :: {type: string, payload: a}
// createAction :: String -> a -> Action a
const createAction = type => payload => ({type, payload});
const SELECT_CARD = 'SELECT_CARD';
const selectCard = createAction(SELECT_CARD); // reducer :: (State, a) -> (State AppState ()) | Null
const reducer = (prevState, {type, payload}) => {
let result;
switch(type) {
case SELECT_CARD:
result = feedback(payload);
break;
default:
result = null;
} return isSameType(State, result) ? result.execWith(prevState): prevState;
} const sillyVerb = createAction('SILLY_VERB'); console.log(
reducer(
state,
selectCard('green-square')
)
)
If we pass the right action, it will return the result, if a bad action, it keep the prev state untouched.
---
const {prop, isSameType, State, 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: 2
}
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 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 feedback = composeK(
applyFeedback,
validateAnswer
)
// Action a :: {type: string, payload: a}
// createAction :: String -> a -> Action a
const createAction = type => payload => ({type, payload});
const SELECT_CARD = 'SELECT_CARD';
const selectCard = createAction(SELECT_CARD); // reducer :: (State, a) -> (State AppState ()) | Null
const reducer = (prevState, {type, payload}) => {
let result;
switch(type) {
case SELECT_CARD:
result = feedback(payload);
break;
default:
result = null;
} return isSameType(State, result) ? result.execWith(prevState): prevState;
} const sillyVerb = createAction('SILLY_VERB'); console.log(
reducer(
state,
selectCard('green-square')
)
)
[Functional Programming ADT] Adapt Redux Actions/Reducers for Use with the State ADT的更多相关文章
- [Functional Programming] Randomly Pull an Item from an Array with the State ADT (Pair)
Functor composition is a powerful concept that arises when we have one Functor nested in another Fun ...
- [React + Functional Programming ADT] Connect State ADT Based Redux Actions to a React Application
With our Redux implementation lousy with State ADT based reducers, it is time to hook it all up to a ...
- Beginning Scala study note(4) Functional Programming in Scala
1. Functional programming treats computation as the evaluation of mathematical and avoids state and ...
- [Functional Programming ADT] Combine Multiple State ADT Based Redux Reducers
Redux provides a convenient helper for combining many reducers called combineReducer, but it focuses ...
- [Functional Programming ADT] Create a Redux Store for Use with a State ADT Based Reducer
With a well defined demarcation point between Redux and our State ADT based model, hooking up to a R ...
- [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 swit ...
- [Functional Programming ADT] Initialize Redux Application State Using The State ADT
Not only will we need to give our initial state to a Redux store, we will also need to be able to re ...
- [Functional Programming] Combine State Dependent Transactions with the State ADT (composeK to replace multi chian call)
When developing a Finite State Machine, it is often necessary to apply multiple transitions in tande ...
- [Functional Programming] Combine Multiple State ADT Instances with the Same Input (converge(liftA2(constant)))
When combining multiple State ADT instances that depend on the same input, using chain can become qu ...
随机推荐
- 继续ajax长轮询解决方案--递归
如果使用for,会有一种情况发生,就是ajax的执行会大于其他的动作的执行,那么这样的一段代码就不能实现了 for(var i=0;i<20;i++){ console.log('你好') $. ...
- CentOS7用yum安装MySQL与启动
首先CentOS7 已经不支持mysql,因为收费了你懂得,所以内部集成了mariadb,而安装mysql的话会和mariadb的文件冲突,所以需要先卸载掉mariadb,以下为卸载mariadb,安 ...
- 【转载】RecyclerView使用全解析
崇拜下鸿洋大神,原文地址:http://blog.csdn.net/lmj623565791/article/details/45059587 概述 RecyclerView出现已经有一段时间了,相信 ...
- python 简单日志框架 自定义logger
转载请注明: 仰望高端玩家的小清新 http://www.cnblogs.com/luruiyuan/ 通常我们在构建 python 系统时,往往需要一个简单的 logging 框架.python 自 ...
- ZOJ 3498 Javabeans
脑筋急转弯. 如果是偶数个,那么第一步可以是$n/2+1$位置开始到$n$都减去$n/2$,后半段就和前半段一样了. 如果是奇数个,那么第一步可以是$(n+1)/2$位置开始到$n$都减去$(n+1) ...
- C++中的error C2662,const的this指针问题
今天在写C++代码的时候遇到一个错误,涉及到了常量的this指针的问题. 简化后的代码如下: #include <iostream> #include <string> usi ...
- You are my brother NBUT - 1218
问题描述 Little A gets to know a new friend, Little B, recently. One day, they realize that they are fam ...
- JZYZOJ1527 [haoi2012]高速公路 线段树 期望
http://172.20.6.3/Problem_Show.asp?id=1527 日常线段树的pushdown写挂,果然每次写都想得不全面,以后要注意啊……求期望部分也不熟练,和平均数搞混也是or ...
- [Codeforces-div.1 809C] Find a car
[Codeforces-div.1 809C] Find a car 试题分析 莫名结论:\(a_{i,j}=(i-1) xor (j-1) +1\) 然后分成\(i\space xor\space ...
- 【并查集】【DFS】搭桥
[codevs1002]搭桥 Description 有一矩形区域的城市中建筑了若干建筑物,如果某两个单元格有一个点相联系,则它们属于同一座建筑物.现在想在这些建筑物之间搭建一些桥梁,其中桥梁只能沿着 ...