The below code is a method for my constructor for the class Word which is part of a word-search app I am building.
createCoordinates () {
let result = []
let printDir = getPrintDirection(this)
let startPos = this.startPos
let coord = {x: startPos.x, y: startPos.y}
for (let i = 0; i < this.text.length; i++) {
result.push (coord)
coord.x = coord.x + printDir.x
coord.y = coord.y + printDir.y
}
return result
}
}
When a new Word is created, the method needs to create an array of board coordinates that the word covers.
Firstly the method creates an empty array: result.
Then it obtains a printDir value (for example {x: 0, y: 1} that dictates how much to change coordinates by for each letter, depending on word direction.
Starting with the startPos value, which is already defined for the word object, it should push a value to the array for each letter in the word, and increment the values in coord according to the direction the word is moving in, and then finally return the array of objects which should reflect all the board squares the word is covering.
So a four letter word moving top to bottom starting at the position: {x: 1, y: 1} should return something like:
[{x:1, y:1}, {x:1, y:2}, {x:1, y:3}, {x:1, y:4}]
From logging inside the loop I can see the coord variable is changing as required, however when I log the array 'result' all the values have become the a different new value which is the value for the letter/iteration after the word should finish. To use the above example the array would look like this:
[{x:1, y:5}, {x:1, y:5}, {x:1, y:5}, {x:1, y:5}]
If I log the progress of the array within the loop, in the 1st iteration I can see that this has already taken place.
I'm stumped by this problem so any help would be appreciated, and I can share all of my code if this would help.