-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.ts
79 lines (68 loc) · 2.03 KB
/
helpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { MAX_COLS, MAX_ROWS } from "./constants";
import { GridType, TileType } from "./types";
const createRow = (row: number, startTile: TileType, endTile: TileType) => {
const currentRow = [];
for (let col = 0; col < MAX_COLS; col++) {
currentRow.push({
row,
col,
isEnd: row === endTile.row && col === endTile.col,
isWall: false,
isPath: false,
distance: Infinity,
isStart: row === startTile.row && col === startTile.col,
isTraversed: false,
parent: null,
});
}
return currentRow;
};
export const createGrid = (startTile: TileType, endTile: TileType) => {
const grid: GridType = [];
for (let row = 0; row < MAX_ROWS; row++) {
grid.push(createRow(row, startTile, endTile));
}
return grid;
};
export const checkIfStartOrEnd = (row: number, col: number) => {
return (
(row === 1 && col === 1) || (row === MAX_ROWS - 2 && col === MAX_COLS - 2)
);
};
export const createNewGrid = (grid: GridType, row: number, col: number) => {
const newGrid = grid.slice();
const newTile = {
...newGrid[row][col],
isWall: !newGrid[row][col].isWall,
};
newGrid[row][col] = newTile;
return newGrid;
};
export const isEqual = (a: TileType, b: TileType) => {
return a.row === b.row && a.col === b.col;
};
export const isRowColEqual = (row: number, col: number, tile: TileType) => {
return row === tile.row && col === tile.col;
};
export const sleep = (ms: number) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
export const getRandInt = (min: number, max: number) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
};
export const checkStack = (tile: TileType, stack: TileType[]) => {
for (let i = 0; i < stack.length; i++) {
if (isEqual(stack[i], tile)) return true;
}
return false;
};
export const dropFromQueue = (tile: TileType, queue: TileType[]) => {
for (let i = 0; i < queue.length; i++) {
if (isEqual(tile, queue[i])) {
queue.splice(i, 1);
break;
}
}
};