I have a class with a property of grid[][]
and each value is either true or false. I need to convert this to a string with letters o and b in place of the boolean.
First way, simple for loops over the array and return the string:
get rle() {
let result = "";
for(let y = 0; y < this.grid.length; y++) {
for(let x =0; x < this.grid[y].length; x++) {
result += ( (this.grid[y][x]) ? "o" : "b" );
}
}
return result;
}
Or a more JS style solution?
get rle() {
return this.grid.reduce( (total, currentValue, currentIndex, arr) => {
return total + arr[currentIndex].reduce( (total, currentValue, currentIndex, arr) => {
return total + ( (arr[currentIndex]) ? "o" : "b" );
}, "");
}, "");
}
Is this a good JS style solution, and what in your opinion is better? I prefer the first because anyone can instantly understand it. The JS solution makes me frown with 3 nested returns, looks odd.