Filtering Actions based on Object.create(null) Typing
Showcase how to create a switch statement in reducers that filters actions based on types created with Object.create(null), ensuring no prototype matches.
const ActionTypes = {
INCREMENT: Object.create(null),
DECREMENT: Object.create(null)
};
// Reducer function
function counterReducer(state = { count: 0 }, action) {
switch (action.type) {
case ActionTypes.INCREMENT:
return { count: state.count + 1 };
case ActionTypes.DECREMENT:
return { count: state.count - 1 };
default:
return state;
}
}
// Dispatching actions
const incrementAction = { type: ActionTypes.INCREMENT };
const decrementAction = { type: ActionTypes.DECREMENT };
console.log(counterReducer(undefined, incrementAction)); // { count: 1 }
console.log(counterReducer({ count: 1 }, decrementAction)); // { count: 0 }
This JavaScript code defines action types using Object.create(null) for creating a unique and prototype-free object. It creates a reducer function (counterReducer) to handle actions based on the types defined. The switch statement within the reducer function checks the type of the action and updates the state accordingly. Two action creators (incrementAction, decrementAction) are also created and dispatched to test the reducer function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Counter Example</title>
<style>
#app {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
#counter {
font-size: 2rem;
}
</style>
</head>
<body>
<div id="app">
<div id="counter">0</div>
</div>
<script src="counter.js"></script>
</body>
</html>
This is an HTML markup with embedded CSS styles for a simple counter display. The HTML structure contains a div with an id of 'app' which houses another div with an id of 'counter' that will be used to display the counter's value. The CSS styles center the counter in the middle of the viewport. The 'counter.js' script (which would include the JavaScript code with ActionTypes and counterReducer) should be placed in the same directory as this HTML file.