Higher-order exercise

by wilsjame

JavaScript

function Automobile( year, make, model, type ){
    this.year = year; //integer (ex. 2001, 1995)
    this.make = make; //string (ex. Honda, Ford)
    this.model = model; //string (ex. Accord, Focus)
    this.type = type; //string (ex. Pickup, SUV)
    this.logMe = function(boolArg){
    	if(boolArg === true){
      	/* print year make model type */
        console.log(this.year + ' ' + this.make + ' ' + this.model + ' ' + this.type);
      }
      else
      {
      	/* print year make model */
        console.log(this.year + ' ' + this.make + ' ' + this.model);
      }
    };
}

var automobiles = [ 
    new Automobile(1995, "Honda", "Accord", "Sedan"),
    new Automobile(1990, "Ford", "F-150", "Pickup"),
    new Automobile(2000, "GMC", "Tahoe", "SUV"),
    new Automobile(2010, "Toyota", "Tacoma", "Pickup"),
    new Automobile(2005, "Lotus", "Elise", "Roadster"),
    new Automobile(2008, "Subaru", "Outback", "Wagon")
    ];

/*This function sorts arrays using an arbitrary comparator. You pass it a comparator and an array of objects appropriate for that comparator and it will return a new array which is sorted with the largest object in index 0 and the smallest in the last index*/
function sortArr( comparator, array ){
	var sortedArr = array; 
  var temp;
  
  /* bubble sort variation */
  for(var i = 0; i < sortedArr.length - 1; i++){
  	for(var j = 0; j < sortedArr.length - 1; j++){
    	if(comparator(sortedArr[j], sortedArr[j + 1]) === false){
      	temp = sortedArr[j];
        sortedArr[j] = sortedArr[j + 1];
        sortedArr[j + 1] = temp;
      }
    }
  }
  return sortedArr;
}

/* test code, it works!
var testArr = [1,5,2,3,4];
var sortedArr = sortArr(exComparator, testArr);
function forE(a, work) {
    for (var i = 0; i < a.length; i++) {
        work(a[i]);
    }
}
function wrapLog(val) {
    console.log(val);
}
forE(sortedArr, wrapLog); 
*/

/*A comparator takes two arguments and uses some algorithm to compare them. If the first argument is larger or...