Last active
February 5, 2019 13:23
-
-
Save adrianmcli/c28e936414c27b5f1dc9efe30cd3b2b2 to your computer and use it in GitHub Desktop.
An example of using plain functions and composing them to make state containers.
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
// state container definition | |
const useState = initVal => { | |
let val = initVal; | |
const get = () => val; | |
const set = x => (val = x); | |
return Object.freeze({ get, set }); | |
}; | |
// make a counter by using the state container | |
const makeCounter = () => { | |
const { get, set } = useState(0); | |
const inc = () => set(get() + 1); | |
const dec = () => set(get() - 1); | |
return Object.freeze({ get, inc, dec }); | |
}; | |
// create the counter object | |
const myCounter = makeCounter(); | |
// let's test our counter out | |
console.log(myCounter.get()); // 0 | |
myCounter.inc(); | |
myCounter.inc(); | |
console.log(myCounter.get()); // 2 | |
myCounter.dec(); | |
myCounter.dec(); | |
console.log(myCounter.get()); // 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment