← Home

André Staltz

@andrestaltz

08 Feb 2016

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.

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

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.

reducer$.fold((acc, reducer) => reducer(acc), state)

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

PS: this is not a blog post, it's a "big tweet".

If you liked this, consider sharing (tweeting) it too.