Skip to content

Instantly share code, notes, and snippets.

@numoonchld
Created August 22, 2021 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save numoonchld/8a0e6468286ef25221ea430f927536fc to your computer and use it in GitHub Desktop.
Save numoonchld/8a0e6468286ef25221ea430f927536fc to your computer and use it in GitHub Desktop.
Redux Modelling
<p>Observe the Console.</p>
import * as Redux from "https://cdn.skypack.dev/redux@4.1.1";
console.clear();
/* people dropping off a form (ACTION CREATORS) */
const createPolicy = (name, policyAmount) => {
return {
// returns a form (ACTION)
type: "CREATE_POLICY",
payload: { name, policyAmount }
};
};
const deletePolicy = (name) => {
return {
type: "DELETE_POLICY",
payload: { name }
};
};
const createClaim = (name, claimAmount) => {
return {
type: "CREATE_CLAIM",
payload: { name, claimAmount }
};
};
/* REDUCERS (departments in the insurance company) */
const claims = (oldSetofClaims = [], action) => {
if (action.type === "CREATE_CLAIM") {
// do the action
return [...oldSetofClaims, action.payload];
}
// dont do anything
return oldSetofClaims;
};
const accounting = (oldBagOfMoney = 100, action) => {
if (action.type === "CREATE_CLAIM") {
return oldBagOfMoney - action.payload.claimAmount;
} else if (action.type === "CREATE_POLICY") {
return oldBagOfMoney + action.payload.policyAmount;
}
return oldBagOfMoney;
};
const policies = (oldPolicies = [], action) => {
if (action.type === "CREATE_POLICY") {
return [...oldPolicies, action.payload];
} else if (action.type === "DELETE_POLICY") {
return oldPolicies.filter(
(policyName) => policyName.name !== action.payload.name
);
}
return oldPolicies;
};
/* ENTER REDUX */
console.log(Redux);
// EXTRACT OUT REDUX FUNCTIONS
const { createStore, combineReducers } = Redux;
/* COMBINE REDUCERS */
const ourDepartments = combineReducers({
claims,
accounting,
policies
});
/* CREATE STORE */
const store = createStore(ourDepartments);
/* DISPATCH ACTIONS */
store.dispatch(createPolicy("Alex", 20));
store.dispatch(createPolicy("Jim", 30));
store.dispatch(createPolicy("Bob", 40));
/* VIEW STATE */
console.log(store.getState());
/* DISPATCH ACTIONS */
store.dispatch(createClaim("Alex", 120));
store.dispatch(createClaim("Jim", 50));
/* VIEW STATE */
console.log(store.getState());
/* DISPATCH ACTIONS */
store.dispatch(deletePolicy("Bob"));
/* VIEW STATE */
console.log(store.getState());
@numoonchld
Copy link
Author

Modelling an Insurance company with pure Redux and plain JavaScript functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment