marijnh / Eloquent-JavaScript

The sources for the Eloquent JavaScript book
https://eloquentjavascript.net
2.99k stars 790 forks source link

Chapter 19 - draw tool #563

Closed hkiame closed 2 years ago

hkiame commented 2 years ago

I find the drawPixel function and draw method in Picture class having extra code or probably I am missing something. The drawPixel function creates an object drawn which is later placed in an array passed as an argument to state.picture.draw method. Would it not be easy to just pass x, y and color as arguments and avoid creating the drawn object, placing it in an array and also avoiding the loop and object destructuring in state.picture.draw method. Below is what I suggest.

    function drawPixel({x, y}, state){
        dispatch({picture: state.picture.draw(x, y, color)});
    }

draw method in Picture class

    draw(x, y, color){
        let copy = this.pixel.slice();
        copy[x + y * this.width] = color;

        return new Picture(this.width, this.height, copy);
    }
marijnh commented 2 years ago

There's other code also calling draw, with arrays of changed pixels.