redux с нуля

This commit is contained in:
Primakov Alexandr Alexandrovich 2025-01-15 09:36:52 +03:00
commit fdab75d633
4 changed files with 132 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
node_modules/

22
package-lock.json generated Normal file
View File

@ -0,0 +1,22 @@
{
"name": "bro-js-redux",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "bro-js-redux",
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"redux": "^5.0.1"
}
},
"node_modules/redux": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
"license": "MIT"
}
}
}

15
package.json Normal file
View File

@ -0,0 +1,15 @@
{
"name": "bro-js-redux",
"version": "1.0.0",
"main": "redux.js",
"scripts": {
"start": "node ."
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"redux": "^5.0.1"
}
}

94
redux.js Normal file
View File

@ -0,0 +1,94 @@
/** bro-js redux start */
const createBroStore = (reducer, state) => {
let _state = state
let _listeners = new Set()
const dispatch = (action) => {
_state = reducer(_state, action)
_listeners.forEach(cb => cb())
}
dispatch({ type: '__INIT__' })
return {
getState: () => _state,
subscribe: callBack => {
_listeners.add(callBack);
return () => _listeners.delete(callBack);
},
dispatch
}
}
const combineReducers = (obj) => (state, action) => {
return Object.keys(obj).reduce((acc, key) => ({
...acc,
[key]: obj[key](state?.[key], action)
}), {})
}
/** bro-js redux end */
let initialState = ['🐙', '🐜']
const ADD_PENGUIN_TYPE = 'add_penguin'
const ADD_CUSTOM_TYPE = 'add_custom'
const ADD_CUSTOM_CAT = 'add_custom_cat'
const animalReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_PENGUIN_TYPE:
return [...state, '🐧'];
case ADD_CUSTOM_TYPE:
return [...state, action.payload]
default:
return state;
}
}
const catsInitialState = {
home: ['😻', '😺']
}
const catsReducer = (state = catsInitialState, action) => {
switch (action.type) {
case ADD_CUSTOM_CAT: return ({
...state,
home: [...state.home, action.payload]
})
default: return state
}
}
const store = require('redux').createStore(combineReducers({
home: (state) => state,
animals: combineReducers({
animal: animalReducer,
cats: catsReducer
})
}))
store.subscribe(() => {
console.log('cats', store.getState().animals.cats)
})
store.subscribe(() => {
console.log('animal', store.getState().animals.animal)
})
console.log(store.getState())
const addPenguin = () => ({ type: ADD_PENGUIN_TYPE })
const addCustom = (custom) => ({ type: ADD_CUSTOM_TYPE, payload: custom })
const addCustomCat = (cat) => ({ type: ADD_CUSTOM_CAT, payload: cat })
store.dispatch(addPenguin())
store.dispatch({ type: '' })
store.dispatch(addCustom('🐬'))
store.dispatch(addCustomCat('😹'))
store.dispatch({ type: '' })