Challenge 13 Filter


#22

Here’s my newest code, reusing the filter function instead of repeating it for each object :slight_smile:

function columnOfIndex(columnIndex){
	return String.fromCharCode(65 + parseInt(columnIndex));
}

function allCoordinates(){
	let coordinates = [];

  for (let row=1; row<=countRows(); row++){
  	for (let columnIndex=0; columnIndex<countColumns(); columnIndex++){
    		coordinates.push(columnOfIndex(columnIndex) + row);
    }
  }
	return coordinates;
}

function filterCoordinates(isObject){
  return allCoordinates().filter(coordinate => {
      return isObject(coordinate);
    });
}

function allRocks(){
	return filterCoordinates(isRock);
}

function allCurrents(){
	return filterCoordinates(isCurrent);
}

function allShips(){
	return filterCoordinates(isShip);
}

#23
function getCoordinates(obstacle){
    let coordinates = [];

    for (let rowIndex=0; rowIndex<countRows(); rowIndex++){
        for (let columnIndex=0; columnIndex<countColumns(); columnIndex++){
            if (GRID[rowIndex][columnIndex] === obstacle) {
                coordinates.push(String.fromCharCode(rowIndex + 97).toUpperCase()+String(columnIndex+1))
            }
        }
    }
    return coordinates;
}

function allRocks(){
    return getCoordinates("^");
}

function allCurrents(){
    return getCoordinates("~");
}

function allShips(){
   return getCoordinates("v");
}

This would be the way without filter and still maintain reusuability :slight_smile: