Skip to content

Commit f672938

Browse files
committed
Add some reducer utils
1 parent 5e18e9c commit f672938

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

foo.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import Alt from './'
2+
import { combine, reduceWith } from './utils/reducers'
3+
4+
const alt = new Alt()
5+
6+
const actions = alt.generateActions('fire', 'foo', 'bar')
7+
8+
const store = alt.createStore({
9+
state: 21,
10+
11+
displayName: 'ValueStore',
12+
13+
reduce: combine(
14+
reduceWith([actions.fire], (state, payload) => {
15+
return state + 1
16+
})
17+
)
18+
})
19+
20+
store.listen(state => console.log('CHANGED', state))
21+
actions.fire()
22+
actions.foo()
23+
actions.bar()
24+
actions.fire()

src/utils/reducers.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { assign } from './functions'
2+
3+
function getId(x) {
4+
return x.id || x
5+
}
6+
7+
function shallowEqual(a, b) {
8+
if (typeof a !== 'object' || typeof b !== 'object') return a === b
9+
if (a === b) return true
10+
if (!a || !b) return false
11+
for (let k in a) {
12+
if (a.hasOwnProperty(k) && (!b.hasOwnProperty(k) || a[k] !== b[k])) {
13+
return false
14+
}
15+
}
16+
for (let k in b) {
17+
if (b.hasOwnProperty(k) && !a.hasOwnProperty(k)) {
18+
return false
19+
}
20+
}
21+
return true
22+
}
23+
24+
export function combine(...restReducers) {
25+
const reducers = assign.apply(null, [{}].concat(restReducers))
26+
return function (state, payload) {
27+
const newState = reducers.hasOwnProperty(payload.action)
28+
? reducers[payload.action](state, payload.data)
29+
: state
30+
31+
if (shallowEqual(state, newState)) this.preventDefault()
32+
33+
return newState
34+
}
35+
}
36+
37+
export function reduceWith(actions, reduce) {
38+
return actions.reduce((total, action) => {
39+
total[getId(action)] = reduce
40+
return total
41+
}, {})
42+
}

0 commit comments

Comments
 (0)