Created
October 1, 2016 23:01
-
-
Save vojtatranta/b412b5c930dc1586a893bda66da8dc90 to your computer and use it in GitHub Desktop.
Bezstavová změna stavu
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// většina tříd má vnitřní stav | |
class Store { | |
constructor(someState) { | |
this._state = someState | |
} | |
setState(state) { | |
this._state = state | |
} | |
getState() { | |
return this._state | |
} | |
} | |
// změna stavu | |
const store = new Store({ count: 0 }) | |
const handleUserClick = () => { | |
const state = store.getState() | |
state.count = state.count + 1 | |
store.setState(state) | |
} | |
// takle přes closure | |
// typická closure memoize, která cachuje výsledek volání funkce na základě parametrů | |
const memoize = (fn) => { | |
var memo = {} | |
return (arg) => { | |
const str = JSON.stringify(arg) | |
if (memo[str]) return memo[str] | |
const result = fn(arg) | |
memo[str] = result | |
return result | |
} | |
} | |
// getter closure | |
const createStore = (initialState) => { | |
var state = initialState | |
const changeState = (newState) => { | |
state = newState | |
} | |
const getState = () => state | |
} | |
// jak "měnit" vnitřní stav tak, ani by byla přepsaná jediná proměnná / property v objektu? | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment