A more flexible and concise "Counter with Redux"

Could you give me your opinion?

// You can have different increment and decrement values ​​simply by assigning different values ​​to INCREMENT and DECREMENT:
const INCREMENT = 1
const DECREMENT = -1

// the action object is destructured
// the value property is used to carry the INC or DEC value
const counterReducer = (state=0, { type, value }) => {
    return [INCREMENT, DECREMENT].includes(type) ? state + value : state
}


// A slightly less concise way to write this reducer:
/*
const counterReducer = (state=0, { type, value }) => {
    if ( type === INCREMENT || type === DECREMENT ) return state + value
    return state
}
*/

const incAction = () => ( { type: INCREMENT, value: INCREMENT } )
const decAction = () => ( { type: DECREMENT, value: DECREMENT } )

const store = Redux.createStore( counterReducer )


// This ad hoc code test must be commented to pass the FCC tests

/*
console.log( store.getState() )

store.dispatch( incAction() )
store.dispatch( incAction() )

console.log( store.getState() )

store.dispatch( decAction() )
console.log( store.getState() )
*/

It’s shorter, but I wouldn’t call it better. Overloading the names of actions with values is not a good idea, and the ternary expression is just code golfing for its own sake. If you’re planning on supporting different amounts of increment/decrement, passing an additional value is useful, but if not, then it’s just added extra noise for no benefit.

Could you explain why?

Do you mean in general overloading actions names with values is a bad idea? (I don’t see the problem for this particular case).

What’s the problem with the ternary expression? (Even I don’t know what do you mean by “golfing”, English is not my native language). I wrote this code is that way because “switch” seems less readable for something so simple.

I understand and I totally agree with your last comment, but the same reasoning is relevant to ask why use redux to store a simple counter, don’t you think?

The redux counter example is a toy, so there’s no real “harm” in adding cleverness to it by overloading the type names with their values. Aside from this Just Not Being Done, idiomatically speaking, the problem comes when you pull up redux dev tools, and your actions look like this: {type: -1, value: -1}. Now, rather than nice readable type names, all you have are numbers.

Code golfing is when you take code and make it shorter, just for the fun of making it shorter. The name comes from the idea of “shaving strokes off” a golf game, where the equivalent in code is to reduce the number of keystrokes. It results in shorter, but not more readable code.

Again, the counter is just a toy app, so doing this to store a simple counter is readable enough. It’s just when you get into bigger apps that you’ll really want to use switch statements to make things more readable.

Now, everything is clear. Thanks.