Skip to content

Commit

Permalink
Lint
Browse files Browse the repository at this point in the history
  • Loading branch information
dylan-chong committed Sep 28, 2023
1 parent 045d2fe commit 693f823
Show file tree
Hide file tree
Showing 6 changed files with 121 additions and 75 deletions.
6 changes: 5 additions & 1 deletion src/components/BoardSelector.vue
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,11 @@ import BoardSelectorCard from "./BoardSelectorCard.vue";
const config = useConfigStore();
const boardText = ref("");
watch(() => config.board, () => setBoardTextFromButtons(), { deep: true });
watch(
() => config.board,
() => setBoardTextFromButtons(),
{ deep: true }
);
const toggleCard = (cardId: number) => {
if (config.board.includes(cardId)) {
Expand Down
87 changes: 53 additions & 34 deletions src/components/HandImporter.vue
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
Import
</button>
<span v-if="importDoneText" class="mt-1">{{ importDoneText }}</span>
<span v-if="importTextError" class="mt-1 text-red-500">Error: {{ importTextError }}</span>
<span v-if="importTextError" class="mt-1 text-red-500">
{{ 'Error: ' + importTextError }}
</span>
</div>

<div class="mt-2">
Expand All @@ -30,10 +32,10 @@ import * as invokes from "../invokes";
type NonValidatedHandJSON = Record<string, any>;
type HandJSON = {
oopRange: string,
ipRange: string,
config: Omit<Config, 'board'> & { board: string[] }
}
oopRange: string;
ipRange: string;
config: Omit<Config, "board"> & { board: string[] };
};
const INVALID_BOARD_ERROR = `Invalid '.config.board'. Set board cards manually for an example.`;
Expand All @@ -44,12 +46,22 @@ const importText = ref("{\n \n}");
const importTextError = ref("");
const importDoneText = ref("");
watch(() => store.ranges, () => generateImportText(), { deep: true });
watch(() => Object.values(config), () => generateImportText(), { deep: true });
watch(
() => store.ranges,
() => generateImportText(),
{ deep: true }
);
watch(
() => Object.values(config),
() => generateImportText(),
{ deep: true }
);
const generateImportText = async () => {
const configObj = Object.fromEntries(
Object.entries(config).filter(([key, _value]) => configKeys.indexOf(key) !== -1)
Object.entries(config).filter(
([key, _value]) => configKeys.indexOf(key) !== -1
)
);
const importObj = {
Expand All @@ -60,47 +72,50 @@ const generateImportText = async () => {
board: config.board.map((cardId) => {
const { rank, suitLetter } = cardText(cardId);
return rank + suitLetter;
})
}
}),
},
};
importText.value = JSON.stringify(importObj, null, 2);
};
const onImportTextChanged = () => {
importDoneText.value = '';
importDoneText.value = "";
validateImportTextAndDisplayError();
}
};
const validateConfigPrimitives = (importConfig: any): Validation => {
if (typeof importConfig !== 'object')
return { success: false, error: `Expected '.config' to be an object but got ${typeof importConfig}` };
if (typeof importConfig !== "object")
return {
success: false,
error: `Expected '.config' to be an object but got ${typeof importConfig}`,
};
for (const key of configKeys) {
const newValue = importConfig[key];
const existingValue = (config as any)[key];
if (existingValue === null || existingValue === undefined) continue;
if (typeof existingValue === typeof newValue) continue;
if (key === 'board')
return { success: false, error: INVALID_BOARD_ERROR };
if (key === "board") return { success: false, error: INVALID_BOARD_ERROR };
else
return {
success: false,
error: `Expected '.config.${key}' to be ${typeof importConfig} but got ${typeof newValue}`
error: `Expected '.config.${key}' to be ${typeof importConfig} but got ${typeof newValue}`,
};
}
return { success: true };
};
const validateBoard = (board: any): Validation => {
if (!Array.isArray(board)) return { success: false, error: INVALID_BOARD_ERROR };
if (!Array.isArray(board))
return { success: false, error: INVALID_BOARD_ERROR };
const boardArr = board as any[];
for (const i in boardArr) {
const card = boardArr[i];
if (typeof card !== 'string') {
if (typeof card !== "string") {
return { success: false, error: INVALID_BOARD_ERROR };
}
Expand All @@ -113,39 +128,43 @@ const validateBoard = (board: any): Validation => {
return { success: true };
};
const parseJson = (json: string): Validation<{ json?: NonValidatedHandJSON }> => {
const parseJson = (
json: string
): Validation<{ json?: NonValidatedHandJSON }> => {
try {
return { success: true, json: JSON.parse(json) };
} catch (e) {
const message = (e as Error).message;
return { success: false, error: message };
}
}
};
const validateImportTextAndDisplayError = (): Validation<{ json?: HandJSON }> => {
importTextError.value = '';
const validateImportTextAndDisplayError = (): Validation<{
json?: HandJSON;
}> => {
importTextError.value = "";
const validation = validateImportText();
if (validation.success) return validation;
importTextError.value = validation.error as string;
return validation;
}
};
const validateImportText = (): Validation<{ json?: HandJSON }> => {
const parseValidation = parseJson(importText.value);
if (!parseValidation.success) return parseValidation;
const importJson = parseValidation.json;
if (typeof importJson !== 'object')
return { success: false, error: 'Not a valid JSON object' };
if (typeof importJson !== "object")
return { success: false, error: "Not a valid JSON object" };
const validateFns: (() => Validation)[] = [
() => validateConfigPrimitives(config),
() => validateBoard(importJson.config?.board),
() => validateRange(importJson.oopRange, 'oopRange'),
() => validateRange(importJson.ipRange, 'ipRange'),
]
() => validateRange(importJson.oopRange, "oopRange"),
() => validateRange(importJson.ipRange, "ipRange"),
];
for (const validate of validateFns) {
const validation = validate();
if (!validation.success) return validation;
Expand All @@ -161,16 +180,16 @@ const importHand = async () => {
if (!validation.success) return;
const importJson = validation.json as HandJSON;
for (let key in importJson.config) {
for (const key in importJson.config) {
const newValue = (importJson.config as Record<string, any>)[key];
(config as any)[key] = newValue;
}
await setRange(Position.OOP, importJson.oopRange, store);
await setRange(Position.IP, importJson.ipRange, store);
importDoneText.value = 'Done!';
importDoneText.value = "Done!";
};
generateImportText();
</script>
</script>
14 changes: 11 additions & 3 deletions src/components/RangeEditor.vue
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,11 @@ const numCombos = ref(0);
let draggingMode: DraggingMode = "none";
watch(() => store.ranges, () => onUpdate(), { deep: true });
watch(
() => store.ranges,
() => onUpdate(),
{ deep: true }
);
const cellText = (row: number, col: number) => {
const r1 = 13 - Math.min(row, col);
Expand Down Expand Up @@ -196,10 +200,14 @@ const update = async (row: number, col: number, weight: number) => {
const onRangeTextChange = async () => {
const validation = validateRange(rangeText.value);
if (!validation.success) {
rangeTextError.value = `Failed to parse range: ${validation.error}`
rangeTextError.value = `Failed to parse range: ${validation.error}`;
}
const assignmentValidation = await setRange(props.player, rangeText.value, store);
const assignmentValidation = await setRange(
props.player,
rangeText.value,
store
);
if (!assignmentValidation.success) {
rangeTextError.value = assignmentValidation.error;
Expand Down
29 changes: 21 additions & 8 deletions src/range-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,28 +12,41 @@ export const rangeRegex = new RegExp(
`^(?<range>${comboPat}(?:\\+|(?:-${comboPat}))?)(?::(?<weight>${weightPat}))?$`
);

const trimRange = (rangeString: string) =>
const trimRange = (rangeString: string) =>
rangeString.replace(trimRegex, "$1").trim();

export const validateRange = (rangeString: any, keyForError: string = 'range'): Validation => {
if (typeof rangeString !== 'string')
return { success: false, error: `Expected '${keyForError}' to be a string but got '${typeof rangeString}` };
export const validateRange = (
rangeString: any,
keyForError = "range"
): Validation => {
if (typeof rangeString !== "string")
return {
success: false,
error: `Expected '${keyForError}' to be a string but got '${typeof rangeString}`,
};

const trimmed = trimRange(rangeString)
const trimmed = trimRange(rangeString);
const ranges = trimmed.split(",");

if (ranges[ranges.length - 1] === "") ranges.pop();

for (const range of ranges) {
if (!rangeRegex.test(range)) {
return { success: false, error: `'${range}' is not a valid range. For an example of a valid range, assign a range manually.` };
return {
success: false,
error: `'${range}' is not a valid range. For an example of a valid range, assign a range manually.`,
};
}
}

return { success: true };
};

export const setRange = async (player: Position, rangeString: string, store: Store): Promise<Validation> => {
export const setRange = async (
player: Position,
rangeString: string,
store: Store
): Promise<Validation> => {
const trimmed = rangeString.replace(trimRegex, "$1").trim();
const validation = validateRange(rangeString);
if (!validation.success) return validation;
Expand All @@ -51,4 +64,4 @@ const loadRangeToStore = async (player: number, store: Store) => {
for (let i = 0; i < 13 * 13; ++i) {
store.ranges[player][i] = weights[i] * 100;
}
};
};
52 changes: 26 additions & 26 deletions src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,32 @@ export type SideView =
| "about";

export type Config = {
board: number[],
startingPot: number,
effectiveStack: number,
rakePercent: number
rakeCap: number
donkOption: boolean,
oopFlopBet: string,
oopFlopRaise: string,
oopTurnBet: string,
oopTurnRaise: string,
oopTurnDonk: string,
oopRiverBet: string,
oopRiverRaise: string,
oopRiverDonk: string,
ipFlopBet: string,
ipFlopRaise: string,
ipTurnBet: string,
ipTurnRaise: string,
ipRiverBet: string,
ipRiverRaise: string,
addAllInThreshold: number,
forceAllInThreshold: number,
mergingThreshold: number,
expectedBoardLength: number
addedLines: string,
removedLines: string,
board: number[];
startingPot: number;
effectiveStack: number;
rakePercent: number;
rakeCap: number;
donkOption: boolean;
oopFlopBet: string;
oopFlopRaise: string;
oopTurnBet: string;
oopTurnRaise: string;
oopTurnDonk: string;
oopRiverBet: string;
oopRiverRaise: string;
oopRiverDonk: string;
ipFlopBet: string;
ipFlopRaise: string;
ipTurnBet: string;
ipTurnRaise: string;
ipRiverBet: string;
ipRiverRaise: string;
addAllInThreshold: number;
forceAllInThreshold: number;
mergingThreshold: number;
expectedBoardLength: number;
addedLines: string;
removedLines: string;
};

export const configKeys = [
Expand Down
8 changes: 5 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// TODO clean up types with generitc type and casts
export type Validation<Contents = {}> = ({ success: true } & Contents) | { success: false, error: string };
export type Validation<Contents = {}> =
| ({ success: true } & Contents)
| { success: false; error: string };

export const ranks = [
"2",
Expand All @@ -23,7 +25,7 @@ export const suitLetters = ["c", "d", "h", "s"];
/** TODO use this everywhere instead of num */
export enum Position {
OOP = 0,
IP = 1
IP = 1,
}

const suitClasses = [
Expand Down Expand Up @@ -335,4 +337,4 @@ export const readableLineString = (s: string): string => {
}

return ret;
};
};

0 comments on commit 693f823

Please sign in to comment.