Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Forked from tjstebbing/butterflymachine.js
Last active October 5, 2015 00:17
Show Gist options
  • Save wilmoore/2721746 to your computer and use it in GitHub Desktop.
Save wilmoore/2721746 to your computer and use it in GitHub Desktop.
Butterfly state machine ( http://harkablog.com/dynamic-state-machines.html ) in javascript
#!/usr/bin/node
/* butterfly state machine */
var Egg = function(species) {
this.species = species;
console.log("An egg");
this.hatch = function() {
this.__proto__ = new Catterpiller();
console.log(this.species, "hatching, check out my", this.legs, "legs!");
}
};
var Catterpiller = function() {
this.legs = 16;
this.crawl = function() {
console.log("crawling");
};
this.eat = function() {
console.log("eating");
};
this.pupate = function() {
this.__proto__ = new Pupa();
console.log(this.species, "Pupating!");
}
};
var Pupa = function() {
this.emerge = function() {
this.__proto__ = new Butterfly();
}
};
var Butterfly = function() {
this.fly = function() {
console.log("flying");
};
this.eat = function() {
console.log("eating");
};
this.reproduce = function() {
return new Egg(this.species);
}
};
critter = new Egg('Morpho menelaus');
critter.hatch();
critter.crawl();
critter.eat();
critter.pupate();
critter.emerge();
critter.fly();
var offspring = critter.reproduce();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment