formatter function moved out for flow/legibility

This commit is contained in:
ak 2023-07-17 13:52:47 -07:00
parent 84982699bf
commit e8e5521371

View file

@ -1,5 +1,31 @@
import { gameBoard } from "./gameBoard.js";
// formatter for final output
const format = (moves) => {
// fix the output array by traversing provided array of BFS search results
// get last square (the destination)
let square = moves[moves.length - 1];
// loop through previous squares until there are no more previous squares (the origin)
// get array of path - made changeable for later
let arr = [];
while (square != null) {
arr.unshift(square);
square = square.prev;
}
// format the output string in the Odin-approved way
let output = `=> You made it in ${
arr.length - 1
} moves! Here's your path:\n`;
// loop through returned array of square objects to return array of positions and append them to the output
for (let i = 0; i < arr.length; i++) {
// change each array index to be the position of the current square object
arr[i] = new Array(arr[i].x, arr[i].y);
// then add it to the output string
output = `${output} [${arr[i]}]\n`;
}
return console.log(output);
};
export const knightMoves = (origin, destination) => {
// make board - 8 x 8
const board = gameBoard(8);
@ -14,31 +40,6 @@ export const knightMoves = (origin, destination) => {
// possible move combinations for x and y - linked at index values - moves clockwise
const possibleX = [1, 2, 2, 1, -1, -2, -2, -1];
const possibleY = [2, 1, -1, -2, -2, -1, 1, 2];
// formatter for final output
const format = (moves) => {
// fix the output array by traversing provided array of BFS search results
// get last square (the destination)
let square = moves[moves.length - 1];
// loop through previous squares until there are no more previous squares (the origin)
// get array of path - made changeable for later
let arr = [];
while (square != null) {
arr.unshift(square);
square = square.prev;
}
// format the output string in the Odin-approved way
let output = `=> You made it in ${
arr.length - 1
} moves! Here's your path:\n`;
// loop through returned array of square objects to return array of positions and append them to the output
for (let i = 0; i < arr.length; i++) {
// change each array index to be the position of the current square object
arr[i] = new Array(arr[i].x, arr[i].y);
// then add it to the output string
output = `${output} [${arr[i]}]\n`;
}
return console.log(output);
};
// initialize looping variables
let current;
const queue = [originSquare];
@ -72,4 +73,4 @@ export const knightMoves = (origin, destination) => {
}
// if not found, return infinity
return Infinity;
};
};