Created
November 15, 2016 19:25
-
-
Save vojtatranta/4742d776e8208617891e7a24cec841e7 to your computer and use it in GitHub Desktop.
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
class ClassLikeCurry { | |
constructor() { | |
this.state = {} | |
} | |
getState() { | |
return this.state | |
} | |
setState(state) { | |
this.state = state | |
} | |
} | |
const curryLikeClass = (state) => ({ | |
getState() { | |
return state | |
}, | |
setState(nextState) { | |
state = nextState | |
} | |
}) | |
// třída je ale horší než curry, protože nedokáže mít state private | |
class ImmutableClass { | |
constructor() { | |
this.state = {} | |
} | |
getState() { | |
return this.state | |
} | |
setState(state) { | |
return new ImmutableClass(state) | |
} | |
} | |
// v JS není nic private | |
const im = new ImmutableClass({a: 'a'}) | |
// hehe změna v pohodě | |
im.state.a = 'b' | |
// curry je trošku lepší | |
// tohle nejde | |
const cls = curryLikeClass({a: 'a'}) | |
// k class se nedostanu jinak než přes: | |
cls.setState({a: 'b'}) | |
// ovšem, javascript je prostě na piču: | |
const state = {a: 'a'} | |
const otherCls = curryLikeClass(state) | |
state.a = 'b' | |
console.log(otherCls.getState()) // -> {a: 'b'} | |
// a to je ten problém, funkcionálnost podle mě dělá immutabilita / schopnost vědět, že se věci změnili | |
// tohle se totiž nedá udělat v jazycích, které mají vše immutable a vše je const - Elm, Haskell... | |
//taková malá legrácka, jak fingovat mutabilitu v immutable světě | |
const createDispatch = (state, whatToCallAfterStateChange) => { | |
return (mutationFn) => { | |
const nextState = Object.assign({}, mutationFn(state)) | |
return whatToCallAfterStateChange(nextState, createDispatch(nextState, whatToCallAfterStateChange)) | |
} | |
} | |
const initialState = { | |
counter: 0, | |
} | |
// Huh, sem dostávám pořád nový state pokaždé, co udělám změnu | |
// tohle funguje i ve funkcionálních jazycích - nikde se tu žádný stav nemutuje, pořád se vytváří nový | |
const onStateChange = (newState, dispatch) => { | |
console.log(newState) | |
const handleDocumentClick = () => { | |
dispatch((oldState) => { | |
oldState.counter++ | |
return oldState | |
}) | |
document.removeEventListener('click', handleDocumentClick) | |
} | |
document.addEventListener('click', handleDocumentClick) | |
} | |
const dispatch = createDispatch(initialState, onStateChange) | |
onStateChange({}, dispatch) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment