[2015-08-12] Challenge #227 [Intermediate] Contiguous chains

JavaScript

First time I trief some ES6 Class stuff. Not sure if it was because it is 2am or if I am just suck, but it went horribly wrong. Still, feedback is always welcome.

class Field {
  constructor(x, y, isOccupied) {
    this.x = x;
    this.y = y;
    this.isOccupied = isOccupied;
  }    


  set chainID(chainID){
    this.chain = chainID;
  }    


  get chainID(){
    return this.chain;
  }
}    


class Map {    

  constructor(input) {
    this.dimensions = {
      x: input[0].length,
      y: input.length
    };    

    this.input = input
    this.fields =[];
  };    


  getField(x, y) {
    if(!this.fields[y]) {
      this.fields[y] = [];
    }    

    if(!this.fields[y][x]) {
      let isOccupied = (this.input[y][x] === 'x');
      this.fields[y][x] = new Field(x, y, isOccupied);
    }    

    return this.fields[y][x];
  };    


  iterate(callback) {
    for(let y = 0; y < this.dimensions.y; y++){
      for(let x = 0; x < this.dimensions.x; x++){
        callback(this.getField(x, y), x, y);
      }
    }
  }
}    



var input = [
  'xxxx xxxx'.split(''),
  '    x    '.split(''),
  '   xx    '.split('')
];    

var chainCount = 0;
var chainPointer = 0;
var chainMap = [];
var map = new Map(input);    


function mergeChains(chainID1, chainID2){
  chainMap[chainID2].forEach((field) => {
    field.chainID = chainID1;
    chainMap[chainID1].push(field);
  })
  chainMap[chainID2] = []; 
  chainCount--;
}    


function sortField(field){
  var topField;
  var leftField    

  if(field.x !== 0) {
    leftField = map.getField(field.x-1, field.y);
    if(leftField.isOccupied){
      field.chainID = leftField.chainID;
    }
  }    


  if(field.y !== 0) {
    topField = map.getField(field.x, field.y-1);
    if(topField.isOccupied){
      if(leftField && leftField.isOccupied){
        mergeChains(topField.chainID, field.chainID);
      }
      field.chainID = topField.chainID;
    }
  }    


  if(field.chainID === undefined){
    field.chainID = chainPointer;
    chainMap[field.chainID] = [];
    chainPointer++;
    chainCount++;
  }     


  chainMap[field.chainID].push(field);    

}    


map.iterate((field, x, y) => {
  if(field.isOccupied){
    sortField(field);
  }
});    

console.log(chainCount);
/r/dailyprogrammer Thread