1

I'm just beginning to learn the use cases for the ES6 WeakMap feature. I've read a lot about it, but I haven't been able to find an answer for this particular question.

I'm implementing a Node.js Minesweeper game for the terminal - just for fun and practice. I've created a class called MineBoard that will store all the necessary data and methods for the game to operate. I want some members, such as _uncoveredCount (number of squares uncovered) and _winningCount (number of squares uncovered needed to win) to remain unaccessible to the user. Although this game isn't going into production, I'd still like it to be uncheatable ;) - and the naming convention of the _ prefix to signal private members is not enough.

To do this - I've implemented a WeakMap to store the two above examples in, and other private members.

METHOD 1:

let _mineBoardPrivateData = new WeakMap();

class MineBoard {
  constructor(size, difficulty) {
    this.size = size || 10;
    this.difficulty = difficulty || 1;
    _mineBoardPrivateData.set(this, {});
    _mineBoardPrivateData.get(this).winningCount = someMethodForDeterminingCount();
    _mineBoardPrivateData.get(this).isGameOver = false;
    _mineBoardPrivateData.get(this).uncoveredCount = 0;
    //more code
  }

  generateNewBoard() {
    //code
  }

  uncoverSquare() {
    //more code
    _mineBoardPrivateData.get(this).uncoveredCount++;
  }

  //more code
}

It is much easier for me to do it this way above - and also much easier on the eyes. However, most of the examples of WeakMap implementations I've seen follow the style below.

METHOD 2:

let _winningCount = new WeakMap();
let _isGameOver = new WeakMap();
let _uncoveredCount = new WeakMap();
//more instantiations of WeakMap here

class MineBoard {
  constructor(size, difficulty) {
    this.size = size || 10;
    this.difficulty = difficulty || 1;
    _winningCount.set(this, someMethodForDeterminingWinningCount() );
    _isGameOver.set(this, false);
    _uncoveredCount.set(this, 0);
    //more private data assignment here
  }

  generateNewBoard() {
    //code
  }

  uncoverSquare() {
    //more code
    _uncoveredCount.set(this, _uncoveredCount.get(this) + 1);
  }

  //more code
}

So my question is - are there any drawbacks to using Method 1 that I am not seeing? This makes for the simpler solution and IMO easier to read and follow code.

Thank you!

1 Answers1

0

You can (and should) use the first method. There are no drawback to using the first method and it probably is more efficient anyways since you're only creating a single object per MineBoard instance. It also means that adding/removing private properties is much easier. Additionally, from inside your MineBoard instance you would be able to easily iterate over all the private properties just using Object.keys(_mineBoardPrivateData.get(this)) (try doing that with the second method).

idbehold
  • 16,833
  • 5
  • 47
  • 74