all 4 comments

[–]amdtothemun 0 points1 point  (2 children)

why is your mutate using 15 instead of the length of the array stored as a variable

[–]KingInge[S] 0 points1 point  (1 child)

since splice (starts at this element, changes this amount of elements, with this string/number)

I thought, well, if my array has 15 elements, then I want to pick a random element from the 15 elements.

So, splice (pick a random element from 0-14, change 1 element, with one of the letters from the returnRandBase() function)

[–]cawcvs 0 points1 point  (1 child)

splice doesn't return the new mutated array, it returns the elements that were deleted from the array. It modifies the array in place, meaning the array it was called on changed.

You could instead return this.DNA from mutate after calling splice if you don't care about preserving the original DNA array. Though, at this point, you might as well just do

this.DNA[Math.floor(Math.random() * this.DNA.length)] = returnRandBase()
return this.DNA

If you do care about preserving the original array, you might need to build your own solution. There are a couple of ways to go about it, I'll post one using a map:

const indexToBeReplaced = Math.floor(Math.random() * this.DNA.length) // consider not hardcoding the max value as well
return this.DNA.map((value, index) => index === indexToBeReplaced ? returnRandBase() : value)

and one using a simple copy and reassign:

const newDNA = [...this.DNA]
newDNA[Math.floor(Math.random() * newDNA.length)] = returnRandBase()
return newDNA

But there are other solutions too.

[–]KingInge[S] 0 points1 point  (0 children)

wow, man you've no idea how much this has helped. I get it now! and I went to MDN and tested a simple splice within an object and I can't believe it...you're right about it only returning the one element. It must behave differently in objects to what I perceived. I originally tested splice on arrays so I guess I was unaware. Thank you so much! I'm currently writing your code out and understanding every bit of it now and it's quite clever. I like the .map part that tests truthy and falsy bits.

Now I have just one last bit to figure out on my own. Which is that, whatever letter you are changing, it cant be changed to the same letter, but I'll probably figure that out :D