-
Notifications
You must be signed in to change notification settings - Fork 96
Nick/lesson19 #41
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Nick/lesson19 #41
Conversation
Add field analizator
Calculate winner with saga
| </div> | ||
| ); | ||
|
|
||
| export const GameState = connect( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
я хоть и не люблю хуки, но с функциональными компонентами они как-то лучше выглядят )
имхо
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А что тебя в этом файле смущает?) Что режет глаз?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Пришли данные - компонент отрисовал, выглядит вроде проще некуда, на первый взгляд
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
много возни с connect/mapStateToProps
ну то есть с хуками ее просто меньше и код плотнее
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Хорошо, попробую подумать
| @@ -0,0 +1,82 @@ | |||
| import { createSlice, PayloadAction } from "@reduxjs/toolkit"; | |||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
может файл slice.ts назваить? так то тут не только редьюсер
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Согласен, тут не только reducer, в соответствии с ducks https://github.com/erikras/ducks-modular-redux
Я привык называть данный файл reducer, можно назвать slice, мне не принципиально
Считаешь, стоит переименовать?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
я не настаиваю ))
| const diagonal1: string[] = []; | ||
| const diagonal2: string[] = []; | ||
|
|
||
| for (let i = 0; i < gameField.length; i++) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
к слову - вроде нет ограничения на квадратность поля
плюс на больших полях считают не только главные диагонали (вроде бы)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это очень хороший поинт! Надо подумать )
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Добавлен код, который исправляет данную ситуацию
| moves: number; | ||
| winner?: string; | ||
| } = { | ||
| fieldSize: defaultFieldSize, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@saitonakamura как ты относиться к typeof initialState ? мне вот это дублирование нифига не нравится
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Поддерживаю) тоже хотел бы так, а так же нужно иметь возможность сделать поле не обязательным
winner?: string;
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
winner: undefined as string | undefined ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@saitonakamura в этом случае он не будет требовать передать туда undefined по умолчанию? Попробую, спасибо
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Будет требовать, но это ж нормально, редьюсер же обычно спредит
Вообще мне что-то пока не очень заходит идея инференса из initialstate
Например нельзя выражать инварианты, много возни с юнионами как выше
Кажется что подход с отдельным стейтом более готовый к реальному коду, хоть и вербозно
src/components/Games/reducer.ts
Outdated
| ...state, | ||
| ...initialState, | ||
| }), | ||
| click: (state, { payload }: ClickActionType) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
вот тут я сомневаюсь )
ClickActionType вроде фукнция же, ReturnType ClickActionType не нужно?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
PayloadAction вроде не функция, можешь проверить плиз?)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
проверил ) все ок
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@saitonakamura а что TS стайлгайд говорить про постфикс Type ? про префик I я помню
в примерах не вижу https://basarat.gitbook.io/typescript/styleguide#type
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
у тс нет официального гайда как такового
но общепринятое примерно так
типы CamelCase
интерфейсы ICamelCase или CamelCase
дженерики TCamelCase
src/components/Games/fieldManager.ts
Outdated
| gameFieldState.map((vector) => | ||
| vector.reduce((acc, item) => { | ||
| if (item === mark) { | ||
| return ++acc; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Почему не acc + 1?
Никаких профитов от мутаций value type мы здесь не получаем вроде
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Да, спасибо, поправлю
|
|
||
| import { createEmptyGameField } from "./fieldManager"; | ||
|
|
||
| export enum GameStatus { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Предпочитаю string literal union, string based енамам: "New game" | "Play" | "Game over"
Енамы хороши для чисел, битовых флагов, но теряют эти преимущества в строках
При этом остаются проблемы
- их 4 вида (enum. const enum, declare enum, declare const enum), каждый немного отличается от другого
- некоторые виды не умеет траспилить бабель
- некоторые виды попадают в рантайм (хотя чаще всего они там не нужны)
- вот это не вызывает ошибки (с числами также)
enum GameStatus {
NewGame = "Play",
Play = "Play",
GameOver = "Play",
}- enum это не закрытое множество и доказать на уровне типов что ты обработал все возможные варианты нельзя
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Спасибо за такой подробный коммент!
| moves: number; | ||
| winner?: string; | ||
| } = { | ||
| fieldSize: defaultFieldSize, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
winner: undefined as string | undefined ?
| <FieldWrapper> | ||
| {field?.map((row, y) => [ | ||
| ...row.map((filled: string, x) => ( | ||
| ...row?.map((filled: string, x) => ( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не особо понял в каких случаях field или row может не быть
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Был сценарий, когда падал storybook, очень неприятно, потом долго пересобирает, лучше обработать
No description provided.