Skip to content

Instantly share code, notes, and snippets.

@mattlockyer
Created June 11, 2019 14:33
Show Gist options
  • Save mattlockyer/d6d983b8b25cf009777209885b17f69f to your computer and use it in GitHub Desktop.
Save mattlockyer/d6d983b8b25cf009777209885b17f69f to your computer and use it in GitHub Desktop.
//helper function
const assignFuncs = (state, funcs) => funcs
.map((func) => ({[func.name]: (...args) => func(state, ...args)}))
.reduce((acc, func) => ({...acc, ...func}))
//example
const bark = (state, howManyTimes) => {
state.barks += howManyTimes
}
const eat = (state, howMuch) => {
state.food -= howMuch
}
const dog = (name) => {
const state = {
name,
barks: 0,
food: 100,
}
return Object.assign(state, {
...assignFuncs(state, [bark, eat]),
})
}
const alfie = dog('Alfie')
alfie.bark(3)
alfie.eat(6)
console.log(alfie.barks) //3
console.log(alfie.food) //94
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment