Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { Set } from 'immutable';
/**
* give the coordinate update the current board with a number choice
* @param x
* @param y
* @param number
* @param fill whether to set or unset
* @param board the immutable board given to change
*/
function updateBoardWithNumber({
x, y, number, fill = true, board,
}) {
let cell = board.get('puzzle').getIn([x, y]);
// delete its notes
cell = cell.delete('notes');
// set or unset its value depending on `fill`
cell = fill ? cell.set('value', number) : cell.delete('value');
const increment = fill ? 1 : -1;
// update the current group choices
const rowPath = ['choices', 'rows', x, number];
const columnPath = ['choices', 'columns', y, number];
const squarePath = ['choices', 'squares',
((Math.floor(x / 3)) * 3) + Math.floor(y / 3), number];
return board.setIn(rowPath, board.getIn(rowPath) + increment)
.setIn(columnPath, board.getIn(columnPath) + increment)
.setIn(squarePath, board.getIn(squarePath) + increment)
.setIn(['puzzle', x, y], cell);
}
class Game extends Compoent {
...
// fill currently selected cell with number
fillNumber = (number) => {
let { board } = this.state;
const selectedCell = this.getSelectedCell();
// no-op if nothing is selected
if (!selectedCell) return;
const prefilled = selectedCell.get('prefilled');
// no-op if it is refilled
if (prefilled) return;
const { x, y } = board.get('selected');
const currentValue = selectedCell.get('value');
// remove the current value and update the game state
if (currentValue) {
board = updateBoardWithNumber({
x, y, number: currentValue, fill: false, board: this.state.board,
});
}
// update to new number if any
const setNumber = currentValue !== number && number;
if (setNumber) {
board = updateBoardWithNumber({
x, y, number, fill: true, board,
});
}
this.setState({ board });
};
addNumberAsNote = (number) => {
let { board } = this.state;
let selectedCell = this.getSelectedCell();
// no-op if nothing is selected
if (!selectedCell) return;
const prefilled = selectedCell.get('prefilled');
// no-op if it is refilled
if (prefilled) return;
const { x, y } = board.get('selected');
let notes = selectedCell.get('notes') || Set();
if (notes.has(number)) {
notes = notes.delete(number);
} else {
notes = notes.add(number);
}
selectedCell = selectedCell.set('notes', notes);
selectedCell = selectedCell.delete('value');
board = board.setIn(['puzzle', x, y], selectedCell);
this.updateBoard(board);
};
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.