Always scope variables with
letorconst. Never use bare variables likemat=0withoutletto scope it to the block. If you have two variables with the same name, or accidentally access a variable when it shouldn't exist, bugs often ensue. Try to tightly scope state as much as possible to reduce complexity.The
Matrixclass doesn't accomplish much, since it consists of a single variable and no functions at the moment. Perhaps soon you'll add operations to it, but for now, a matrix can simply be a variable. Classes are primarily useful when you want to group a bunch of related variables and functions together, and establish a set of rules for accessing and manipulating that state.Once you do add a class, you'll probably not want to let the user of the class access the
.Mproperty directly, or they could mess up state within the class.Avoid counter-based
forloops unless necessary. Preferfor ... ofloops; they look cleaner and are less prone to off-by-one bugs. Caveat: sometimes, for performance reasons,forloops are acceptable, but I'd avoid premature optimization.Use prettier to format your code in a way that reduces the friction for yourself and other JS programmers to read your code.
Since you never reassign
let matrices = [];, you can useconst matrices = [];. This avoids an accidental reassignment and more accurately communicates your intent.Since
matricesis unrelated to P5 you can move it out of thesetupfunction and simply declare it once, without modifying the array withpush.textSize(20);is always the same in the middle of the loops, so you can save some CPU cycles by moving it outside of the loops so it runs once per frame.Code like
text( matrices[mat].M[row][col], 500+20*col, 100+120*mat+30*row);is difficult to read because there are many operations on one line and no named parameters. You can move the arguments out to named variables,value,xandy, then usetext(value, x, y). Another trick I like to use for calls like this is to spread it across multiple lines, with comments to denote each parameter by name:text( matrices[mat].M[row][col], 500 + 20 * col, // x 100 + 120 * mat + 30 * row // y );As the program grows, breaking the
drawfunction into helpers, likedrawMatrices, would be good.Consider making the application more friendly to various screens with dynamic sizes (not done in my rewrite below, but left as an exercise). You can see my version overflows the screen.