Skip to content

Instantly share code, notes, and snippets.

View t-t-t-action-replay-5.js
cellView.addEventListener('click',
() => gameEngine.handleEvent(
{
name: 'turn-taken-event',
player: viewModel.currentPlayer,
row: rIndex,
col: cIndex,
gameboard: gameBoard
}));
@priort
priort / t-t-t-action-replay-1.js
Last active Jan 2, 2021
Tic-Tak-Toe-with-Action-Replay-Snippet-1
View t-t-t-action-replay-1.js
const tests = () => {
let testsPassed;
let gameboardWithNoCompletedRowsOrColumnsButAllCellsCompleted = [
['X','O', 'X'],
['O','O', 'X'],
['O','X', 'O']
]
testsPassed = !winChecker.thereIsAWinner(gameboardWithNoCompletedRowsOrColumnsButAllCellsCompleted);
console.log('Test thereIsAWinner gameboardWithNoCompletedRowsOrColumnsButAllCellsCompleted ' + testsPassed);
View t-t-t-action-replay-4.js
let handleTurnTaken = (turnTakenEvent) => {
if(turnTakenEvent.gameboard[turnTakenEvent.row][turnTakenEvent.col] !== 'X' && turnTakenEvent.gameboard[turnTakenEvent.row][turnTakenEvent.col] !== 'O') {
console.log('Player ' + turnTakenEvent.player + ' has taken a turn');
let nextPlayer = turnTakenEvent.player === 'O' ? 'X' : 'O';
let nextGameBoard = turnTakenEvent.gameboard.map(
(row, rIndex) => {
return row.map((col, cIndex) => {
return rIndex === turnTakenEvent.row && cIndex === turnTakenEvent.col ?
turnTakenEvent.player : col
View t-t-t-action-replay-3.js
let view = function() {
let viewModel = {
currentPlayer: 'X',
winner: null
};
let gameBoard = new Array(3).fill(new Array(3).fill(''));
eventDispatcher.subscribe('game-board-updated-event', gameBoardUpdatedEvent => {
viewModel.currentPlayer = gameBoardUpdatedEvent.nextPlayer;
View t-t-t-action-replay-2.js
let eventDispatcher = function() {
let replaying = false;
let events = [];
let subscribers = {};
let dispatchEvent = (ev) => {
if (!replaying) {
events.push(ev);
}
for (const sub of subscribers[ev.name]) {
View PersistTheList6.kt
fun <E> dropWhile(list: List<E>, f: (E) -> Boolean): List<E> =
when(list) {
Empty -> Empty
is Cons -> if (f(list.head)) dropWhile(list.tail, f) else list
}
fun main() {
val myList = Cons(1, Cons(2, Cons(3, Cons(4, Empty))))
dropWhile(myList) { it < 3 }.let(::println)
View PersistTheList7.kt
tailrec fun <E> dropWhile(list: List<E>, f: (E) -> Boolean): List<E> =
when(list) {
Empty -> Empty
is Cons -> if (f(list.head)) dropWhile(list.tail, f) else list
}
View PersistTheList8.kt
fun <E> dropWhile(list: List<E>, f: (E) -> Boolean): List<E> {
tailrec fun loop(remaining: List<E>): List<E> =
when(remaining) {
is Empty -> remaining
is Cons -> if (f(remaining.head)) loop(remaining.tail) else remaining
}
return loop(list)
}
View PersistTheList5.kt
sealed class List<out E>
object Empty: List<Nothing>() {
override fun toString()= "[]"
}
data class Cons<E>(val head: E, val tail: List<E>): List<E>() {
override fun toString(): String = "$head :: $tail"
}
fun main() {
View PersistTheList4.kt
fun dropWhile(list: List<Int>, f: (Int) -> Boolean)