Skip to content

Instantly share code, notes, and snippets.

@dschinkel
Last active July 16, 2018 07:50
Show Gist options
  • Select an option

  • Save dschinkel/9b68c7e30c7cf59a903b3cbf6ea82fb4 to your computer and use it in GitHub Desktop.

Select an option

Save dschinkel/9b68c7e30c7cf59a903b3cbf6ea82fb4 to your computer and use it in GitHub Desktop.
Medium Blog Post - Data Hiding, Instances, and Better Testing with JS Factories and Closures
import { Marker } from './Constants';
const { EMPTY_CELL } = Marker;
function _Board(grid) {
if(!grid){
grid = [
EMPTY_CELL, EMPTY_CELL, EMPTY_CELL,
EMPTY_CELL, EMPTY_CELL, EMPTY_CELL,
EMPTY_CELL, EMPTY_CELL, EMPTY_CELL];
}
function cellIsEmpty(position){
return grid[position] === EMPTY_CELL;
}
function getEmptyCells(){
const emptyCells = grid.filter((cell) => {
return cell === EMPTY_CELL
});
return emptyCells;
}
function getEmptyCellIndexes(){
const indexes = [];
for(let [i, cellValue] of grid.entries()) {
if (cellValue === EMPTY_CELL){
indexes.push(i);
}
}
return indexes;
}
// return a copy of grid so clients have their own copy to play with & mutate
function getGrid() {
return grid.slice();
}
function isFull(){
const emptyCells = grid.filter(cell => { return cell === EMPTY_CELL});
return emptyCells.length === 0;
}
function addMove(position, marker){
grid.splice(position, 1, marker);
}
// return a new Board instance with current state copied into the new instance
function clone() {
return Board(getGrid());
}
// return the public API we'd like to expose
return {
addMove,
getGrid,
clone,
isFull,
getGrid,
getEmptyCells,
getEmptyCellIndexes,
cellIsEmpty
};
}
function Board(grid) {
// we return an invocation of _Board() which ultimately returns our API
// which the caller will use for this newly created instance of Board()
return _Board(grid);
}
export default Board;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment