Modular Architect

Composition testing

by black strings

JavaScript

// ## --- Dog class
/* var Dog = function(name) {
    this.name = name;
};
Dog.prototype.bark = function(){
    console.log(this.name + ' bark');
}
Dog.prototype.clone = function(){
  return this.constructor(this.name);
}
 */
 
class Component {
	constructor(){
  	this.components = [];
  }
  add(component){
  	this.components.push(component);
  }
  remove(component){
  	if(this.components.contains(component)){
    	this.components.remove(component);
    }
  }
  has(func){
    for(var i=0; i<this.components.length; i++){
    	var comp = this.components[i];
    	if(func(comp)){
      	return comp;
      }
    }
    return null;
  }
}

class Dog extends Component {
	constructor(name){
  	super();
  	this.name = name;
  }
	bark(){
  	console.log(this.name + ' bark');
  }
  clone(){
  	return new this.constructor(this.name);
  }
}

// ## --- BullDog class
class BullDog extends Dog {
	constructor(name){
  	super(name);
  }
	
  jump(){
  	console.log(this.name + ' jumping');
  }
  
  slam(){
  	this.has(comp => {comp instanceof Hammer ? comp.slam() : null });
  }
  
  fly(){
  	this.has(comp => {comp instanceof Fly ? comp.fly() : null });
  }
}

class Hammer extends Component {
	constructor(){
  	super();
  }
  slam(){
  	console.log('slaming');
  }
}

class Fly extends Component {
	constructor(){
  	super();
  }
  fly(){
  	console.log('flying');
  }
}


// -------------- Test ----------------
// Dog
var d = new Dog('Sam');
d.bark();
//d.jump(); // error - as Dog is not a bulldog


// BullDog
var b = new BullDog('Bob');
b.bark();	// works
b.jump();	// works


// Clone the bullDog - we get a Dog instead of a BullDog
var c = b.clone();
c.bark(); 	//work
c.jump();	// error

var h = new Hammer();
b.add(h);
b.slam();

b.add(new Fly());
b.fly();