app/position.js

const { COORDS, LOST, EMPTY_STRING, BLANK_SPACE } = require('../utils')

class Position {
  /**
   * Sets the default values for a position:
   * - Coordinates are 0,0
   * - Orientation is North (N)
   * - Lost is false
   */
  constructor () {
    this.x = 0
    this.y = 0
    this.orientation = COORDS.N
    this.lost = false
  }

  /**
   * Returns the position (`X Y Orientation`) as string in one line. If lost is true, includes 'LOST' text.
   * @returns {string}
   */
  toString () {
    const lostText = this.lost ? (BLANK_SPACE + LOST) : EMPTY_STRING
    return `${this.x} ${this.y} ${this.orientation}${lostText}`
  }

  /**
   * Check if robot is off the grid. If it's, sets `lost` to true
   * @param grid {Grid}
   * @returns {boolean} Returns `true` if the robot is off the grid
   */
  isOffTheGrid (grid) {
    // If is off the grid
    if (this.x > grid.length || this.y > grid.height || this.y < 0 || this.x < 0) {
      // Max value for `y`
      if (this.orientation === COORDS.N) {
        this.y = grid.height
      }
      if (this.orientation === COORDS.S) {
        this.y = 0
      }
      // Max value for `x`
      if (this.orientation === COORDS.E) {
        this.x = grid.length
      }
      if (this.orientation === COORDS.W) {
        this.x = 0
      }

      this.lost = true
      return this.lost
    }
    return false
  }
}

module.exports = Position