Skip to content

Instantly share code, notes, and snippets.

@OlIvAl
Created March 2, 2020 14:30
Show Gist options
  • Save OlIvAl/5c9710336040d760e7d73cf593ba2e78 to your computer and use it in GitHub Desktop.
Save OlIvAl/5c9710336040d760e7d73cf593ba2e78 to your computer and use it in GitHub Desktop.
pagination and filter
import { IFilter, IFilterOptionsObject } from './interfaces';
import { action, computed, observable } from 'mobx';
import isEqual from 'lodash/isEqual';
export class Filter<T> implements IFilter<T> {
filterDefaultValue: T;
@observable filterSelectOptions: IFilterOptionsObject<T> | null = null;
@computed get notDefaultFilterObject(): Partial<T> {
return (Object.keys(this.filterObject) as (keyof T)[]).reduce<Partial<T>>((acc, key): Partial<
T
> => {
if (!this.filterObject || isEqual(this.filterObject[key], this.filterDefaultValue[key])) {
return acc;
}
return {
...acc,
[key]: this.filterObject[key]
};
}, {});
}
@observable filterObject: T;
constructor(filterDefaultValue: T) {
this.filterDefaultValue = filterDefaultValue;
this.filterObject = filterDefaultValue;
}
@action.bound setFilterObject(newFilterObject: T): void {
this.filterObject = newFilterObject;
}
@action.bound setFilterSelectOptions(newFilterSelectOptions: IFilterOptionsObject<T>): void {
this.filterSelectOptions = newFilterSelectOptions;
}
@action.bound reset(): void {
this.setFilterObject(this.filterDefaultValue);
}
}
import { IPagination, IPaginationObject } from './interfaces';
import { action, computed, observable, reaction } from 'mobx';
export default class Pagination implements IPagination {
@observable page: number = 0;
@observable pageSize: number = 0;
@computed get paginationObject(): IPaginationObject {
return {
offset: this.page * this.pageSize,
limit: this.pageSize
};
}
@computed get pages(): number {
return Math.ceil(this.itemsLength / this.pageSize);
}
@computed get canPrevious(): boolean {
return this.page > 0;
}
@computed get canNext(): boolean {
return this.page < this.pages - 1;
}
/**
* Общее количество элементов
*/
@observable private itemsLength: number = 0;
constructor(offset: number, limit: number) {
this.pageSize = limit;
this.page = Math.floor((offset) / this.pageSize);
reaction<number>(
() => this.itemsLength,
(itemsLength: number): void => {
// if new items total < offset
if (itemsLength < this.page * this.pageSize) {
this.page = 0;
}
}
);
}
@action.bound setItemsLength(newItemsLength: number): void {
this.itemsLength = newItemsLength;
}
@action.bound pageChange(newPage: number): void {
this.page = newPage;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment