Skip to content

Conversation

@nickovchinnikov
Copy link
Owner

No description provided.

</div>
);

export const GameState = connect(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

я хоть и не люблю хуки, но с функциональными компонентами они как-то лучше выглядят )
имхо

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А что тебя в этом файле смущает?) Что режет глаз?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Пришли данные - компонент отрисовал, выглядит вроде проще некуда, на первый взгляд

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

много возни с connect/mapStateToProps
ну то есть с хуками ее просто меньше и код плотнее

Copy link
Owner Author

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";
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

может файл slice.ts назваить? так то тут не только редьюсер

Copy link
Owner Author

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, мне не принципиально
Считаешь, стоит переименовать?

Copy link
Collaborator

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++) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

к слову - вроде нет ограничения на квадратность поля

плюс на больших полях считают не только главные диагонали (вроде бы)

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это очень хороший поинт! Надо подумать )

Copy link
Owner Author

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,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@saitonakamura как ты относиться к typeof initialState ? мне вот это дублирование нифига не нравится

Copy link
Owner Author

@nickovchinnikov nickovchinnikov Jun 7, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поддерживаю) тоже хотел бы так, а так же нужно иметь возможность сделать поле не обязательным
winner?: string;

Copy link
Contributor

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 ?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@saitonakamura в этом случае он не будет требовать передать туда undefined по умолчанию? Попробую, спасибо

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Будет требовать, но это ж нормально, редьюсер же обычно спредит
Вообще мне что-то пока не очень заходит идея инференса из initialstate
Например нельзя выражать инварианты, много возни с юнионами как выше
Кажется что подход с отдельным стейтом более готовый к реальному коду, хоть и вербозно

...state,
...initialState,
}),
click: (state, { payload }: ClickActionType) => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

вот тут я сомневаюсь )

ClickActionType вроде фукнция же, ReturnType ClickActionType не нужно?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PayloadAction вроде не функция, можешь проверить плиз?)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

проверил ) все ок

Copy link
Collaborator

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

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

у тс нет официального гайда как такового
но общепринятое примерно так
типы CamelCase
интерфейсы ICamelCase или CamelCase
дженерики TCamelCase

gameFieldState.map((vector) =>
vector.reduce((acc, item) => {
if (item === mark) {
return ++acc;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Почему не acc + 1?
Никаких профитов от мутаций value type мы здесь не получаем вроде

Copy link
Owner Author

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 {
Copy link
Contributor

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 это не закрытое множество и доказать на уровне типов что ты обработал все возможные варианты нельзя

Copy link
Owner Author

@nickovchinnikov nickovchinnikov Jun 11, 2020

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,
Copy link
Contributor

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) => (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не особо понял в каких случаях field или row может не быть

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Был сценарий, когда падал storybook, очень неприятно, потом долго пересобирает, лучше обработать

@nickovchinnikov nickovchinnikov merged commit c368b66 into master Jun 11, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants