Skip to content

Latest commit

 

History

History
26 lines (19 loc) · 1.53 KB

2016-02-08-reducer-pattern-in-cyclejs.md

File metadata and controls

26 lines (19 loc) · 1.53 KB
layout title tags
big-tweet
The reducer pattern in Cycle.js
bigtweet

The “reducer” pattern from Redux (or the “update” pattern from the Elm architecture) is common also in Cycle.js, except there is no switch-case (or pattern matching block) because each reducer corresponds to one (and only one) action.

See this example code where each action stream is being mapped to a “reducer” function.

{% highlight js %} const setHighlightReducer$ = actions.setHighlight$ .map(highlighted => function setHighlightReducer(state) { return state.set('highlighted', highlighted) }) {% endhighlight %}

This produces a stream of reducer functions, which we can then merge all together to get just one stream of reducer functions.

The stream of reducer functions is then “reduced” with the fold operator. This is how state is accumulated over time.

{% highlight js %} reducer$.fold((acc, reducer) => reducer(acc), state) {% endhighlight %}

The benefit is freedom from switch-case blocks, and a good semantic connection between reducer and action.