Skip to content

Instantly share code, notes, and snippets.

@adrianmcli
Last active February 5, 2019 13:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adrianmcli/c28e936414c27b5f1dc9efe30cd3b2b2 to your computer and use it in GitHub Desktop.
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.
// 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