Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Last active February 19, 2016 16:31
Show Gist options
  • Save ericelliott/9ddf8562ca3826af238d to your computer and use it in GitHub Desktop.
Save ericelliott/9ddf8562ca3826af238d to your computer and use it in GitHub Desktop.
Black box composition example
const pooper = (delay) => {
return {
lastPoop: null,
getPoopDelay () { return delay; },
canPoop: function(now) {
return this.lastPoop ? (this.lastPoop + delay) >= now : true
},
poop: function(){
if(this.canPoop(new Date())){
//implementation for pooping is omitted
this.lastPoop = new Date();
}
}
}
};
const eater = (delay) => {
return {
lastMeal: null,
getEatDelay () { return delay; },
canEat: function(now) {
return this.lastMeal ? (this.lastMeal + delay) >= now : true
},
eat: function(food){
if(this.canEat(new Date())){
//implementation for eating is omitted
this.lastMeal = new Date();
}
}
};
};
const dog = (poopDelay, eatDelay, pooper, eater) => Object.assign({}, pooper(poopDelay), eater(eatDelay));
let myDog = dog(4, 8, pooper, eater);
console.log(myDog.getPoopDelay()) //4
console.log(myDog.getEatDelay()) //8
@craigbilner
Copy link

Hi, does this.delay need tidying up?

@ericelliott
Copy link
Author

Yes. Done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment