clockworkgeek/bolide

choose better data structures

clockworkgeek opened this issue · 2 comments

Coders tend to choose arrays for everything but that isn't always the best. e.g. In sketch.js there is:

let targets = [];
let friendly = [];
let enemy = [];
let stars = [];
let overlay = [];

But those could be sets instead:

let targets = new Set();
let friendly = new Set();
let enemy = new Set();
let stars = new Set();
let overlay = new Set();

Then in function setup() those are reset clumsily by reassigning, but that could be:

  targets.clear();
  friendly.clear();
  friendly.add(ship);
  enemy.clear();
  stars.clear();
  overlay.clear();

Elsewhere this would much simplify things, like lasers could now say:

  remove() {
    friendly.delete(this);
    enemy.delete(this);
  }

The savings go throughout and there are no downsides except for the need to test what you write.

@clockworkgeek I hadn't forgotten or intentionally neglected your homework assignment to convert some arrays to sets. But I'm still catching up with the basic structure of your foundations, and was thinking I'd like to master what we started before do these conversions. It seems like this conversion to sets could be considered a fairly substantial refactor, no?

If it is left now you will have more array-related code to change later. Data is fundamental.

“In fact, I’m a huge proponent of designing your code around the data, rather than the other way around…Bad programmers worry about the code. Good programmers worry about data structures and their relationships.”
— Linus Torvalds