Skip to content

Instantly share code, notes, and snippets.

@maxpou
Created April 9, 2018 18:48
Show Gist options
  • Save maxpou/bfd7bbb62c57ca44053744c535acc570 to your computer and use it in GitHub Desktop.
Save maxpou/bfd7bbb62c57ca44053744c535acc570 to your computer and use it in GitHub Desktop.
composition over inheritance
const canStar = state => ({
star() {
state.nbStar++
}
})
const canFork = state => ({
fork() {
state.nbFork++
}
})
const repository = name => {
let state = {
name,
nbStar: 0,
nbFork: 0
}
return { ...state, ...canStar(state), ...canFork(state) }
}
const gist = name => {
let state = {
name,
nbStar: 0
}
return { ...state, ...canStar(state) }
}
// ////////// //
// Playground
// ////////// //
const aRepo = repository("docker")
aRepo.star()
aRepo.star()
aRepo.fork()
console.log(aRepo)
// {
// name: 'docker',
// nbStar: 0,
// nbFork: 0,
// star: [Function: star],
// fork: [Function: fork]
// }
const aGist = gist("composition.js")
aGist.star()
console.log(aGist)
// {
// name: 'composition.js',
// nbStar: 0,
// star: [Function: star]
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment