Skip to content

feat: add pagination #92

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

Open
wants to merge 1 commit into
base: lecture-6
Choose a base branch
from

Conversation

nikolaevfo
Copy link

No description provided.

Copy link
Owner

@Letto228 Letto228 left a comment

Choose a reason for hiding this comment

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

Привет!
Классная директива вышла, оставил несколько вопросов/пердложений, посмотри, пожалуйста

@@ -0,0 +1,8 @@
export interface IPaginationContext<T> {
Copy link
Owner

Choose a reason for hiding this comment

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

Я бы добавил еще appPaginationOf для того, чтобы передавать значение инпута в контексте

@Input() appPaginationChankSize = 6;

private readonly currentPage$ = new BehaviorSubject<number>(0);
private readonly pageIndexes = [1, 2, 3];
Copy link
Owner

Choose a reason for hiding this comment

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

А это значение где-то используется?


private readonly currentPage$ = new BehaviorSubject<number>(0);
private readonly pageIndexes = [1, 2, 3];
private readonly activeIndex = 1;
Copy link
Owner

Choose a reason for hiding this comment

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

И это значение разве где-то используем? Не дублирует ли оно по значению currentPage$?

private readonly currentPage$ = new BehaviorSubject<number>(0);
private readonly pageIndexes = [1, 2, 3];
private readonly activeIndex = 1;
private pagesCount: number | undefined;
Copy link
Owner

Choose a reason for hiding this comment

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

Может зададим initial value, таким образом избавимся от | undefined в типизации

) {}

ngOnChanges({appPaginationOf}: SimpleChanges): void {
if (appPaginationOf) {
Copy link
Owner

Choose a reason for hiding this comment

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

А при зименении appPaginationChankSize нам не стоит выполнить updateView ?

private getCurrentContext(currentPage: number): IPaginationContext<T> {
const startProduct = currentPage * this.appPaginationChankSize;
const endProduct = (currentPage + 1) * this.appPaginationChankSize;
const pages = this.appPaginationOf!.slice(startProduct, endProduct);
Copy link
Owner

Choose a reason for hiding this comment

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

Я бы все эти вычисления рекомендовал вынести в отдельную чистую функцию - это поможет разгрузить метод

Copy link
Author

Choose a reason for hiding this comment

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

чистую функцию стоит выносить из кода директивы, или можно внутри класса оставить?

Copy link
Owner

Choose a reason for hiding this comment

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

Лучше вынести из кода директивы, чтобы не засорять класс функциями, которые на нем не завязаны


let pageIndexes: number[];

if (currentPage === 0) {
Copy link
Owner

Choose a reason for hiding this comment

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

Мы с тобой не обсуждали, что else/if - не лучшая практика?)
Если нет - могу подкинуть аргументов, если интересно, только дай знать🙃

Copy link
Owner

Choose a reason for hiding this comment

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

Вообще, все что ниже, стоит вынести в отдельную чистую функцию, чтобы так же разгрузить метод, назвать ее можно getPageIndexes(currentPage, this.pagesCount)

Copy link
Author

Choose a reason for hiding this comment

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

на счет else/if, на ум приходит только switch/case. здесь он будет норм?

Copy link
Owner

Choose a reason for hiding this comment

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

Нет, я не в сторону того, что if тут не пождходит, он отлично справляется с поставленной задачей

Глобально есть 2 подхода: ранний return и if/else.

Соответсвенно у каждого подхода есть свои поклонники и противники. Соответсвенно я отношу себя к сторонникам раннего return и противником if/else. Почему? - ранний return более гибкий и читается в разы проше из-за того, что условие можно в нужный момент декомпозировать на констатны и сделать код легко читаемым, прям как книжку:

const propFirst = ...;
const propLast = ...;

if (propFirst) {
...
} else if (propLast) {
...
else {
...
}

А теперь представь, что везде вместо ... n-е количество кода. Просто ли это будет читаться? Мне кажется не очень.

Теперь же другой подход:

const propLast = ...;

if (propFirst) {
    ...

    return;
}

const propFirst = ...;

if (propLast) {
     ...
     
     return;
}

...

Код делает одно и то же, но в раннем ретерне все константы могут быть вычислены при необходимости, а в if/else их необходимо вычислять в самом начале. К тому же из-за явного выделения if, отступами в том числе, мы улучшаем читаемость

@@ -38,6 +38,8 @@ export class CarouselDirective<T> implements OnChanges, OnInit {

if (shouldShowItems) {
this.currentIndex$.next(0);

return;
Copy link
Owner

Choose a reason for hiding this comment

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

Ух ты, вот это мы на лекции пропустили, спасибо что подметил, поправлю у себя!

@Letto228
Copy link
Owner

Letto228 commented Dec 4, 2023

@nikolaevfo Дал ответ по комментариям твоим, посмотри, пожалуйста

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.

2 participants