Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

uncaught typeerror in class despite setting element

So I’m making a basic brute force sudoku solver. I created a class that takes in a board string and use a constructor to set this.board = board parameter passed in

export default class SudokuSolver {
  constructor(board){
    this.board = board
  }

the first method that gets run is validBoardFormat

validBoardFormat(){
    /* possible input formats: CSV of 81 integers or string of 81 integers
    0's replace unknown numbers*/
    let cleanedBoard=[];
    let uncleanedBoard = this.board.split('') //split by character
    for (let i = 0; i<uncleanedBoard.length; i++){
      if (this.validNum(uncleanedBoard[i])){ //validate with validNum function
        cleanedBoard.push(parseInt(uncleanedBoard[i]))
      }
    }
    if (cleanedBoard.length === 81){ 
      this.board = cleanedBoard //make sure board matches correct sudoku board length
      return true
    }
    return false
  }

Let’s say for example pass in:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let boardString = "1024091501202523235" //imagine this is a valid board string
const board = new SudokuSolver(boardString)
console.log(board.validBoardFormat())

console: true

This works perfectly fine on its own.

later in the class I define a solve method

solve(){
    if (this.validBoardFormat()){
        this.validBoardFormat()
        this.configureBoardArray()
        this.solveBoard()

    } else {
      console.log('Board error')
    }
  }

The issue is when I pass this:

let boardString = "1024091501202523235" //imagine this is a valid board string
const board = new SudokuSolver(board)
console.log(board.solve())

and I run it on liveserver, I am getting this error:

Uncaught TypeError: this.board.split is not a function in the validBoardFormat function

I have been trying to troubleshoot this for a while now any help would be appreicated

>Solution :

You’re setting this.board to an array:

if (cleanedBoard.length === 81){
  this.board = cleanedBoard // <= this.board is now an array
  return true
}

So the next time you call validBoardFormat() you end up trying to invoke split on the array, not the string:

let uncleanedBoard = this.board.split('') // this.board is now an array, not a string
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading