Quick Console Sandbox

do stuff

by nickadeemus2002

JavaScript

/**
* JS function overloading
*/

// add object methods that will
// execute different logic based on 
// the arguments passed to addMethod
function addMethod(obj, name, fn){
	var stored = obj[name];
  console.log('obj', obj);
  console.log('name', name);
  console.log('fn', fn);
  console.log('stored', stored);  
  
  obj[name] = function(){
    if(fn.length === arguments.length){
    	return fn.prototype.apply(this, arguments);
    }
    else if(typeof stored === 'function'){
    	return stored.prototype.apply(this, arguments);
    }
  };
}


//create object
var students = {
	honorRoll: [ 
  						{ firstName: "Makayla", lastName: "Villanueva"},
              { firstName: "Kathryn", lastName: "Villanueva"},
              { firstName: "Chris", lastName: "Villanueva"},
              { firstName: "Cindy", lastName: "Villanueva"}
  					 ]            
};

// add a "get" method to students
// that returns different results determined
// by arguments passed to "get" method

//get all
addMethod(students, "get", function(){ 
	return this.honorRoll;
});

//get by index
addMethod(students, "get", function(idx){
	return this.honorRoll[idx];
});

//get by name
addMethod(students, "get", function(firstName, lastName){
	return this.honorRoll.filter(function(student){
  	if(student.firstName === firstName && student.lastName === lastName){
    	return student;
    }
  });
});