A TypeScript class for paginating an array.
export type ArrayPaginatorSettings<T> = {
/*****
Defaults to most recent setting, or if not set, empty array
*****/
array?: T[];
/*****
Defaults to most recent setting, or if not set, 25
*****/
pageLength?: number;
/*****
Defaults to most recent setting, or if not set, 1
*****/
pageNumber?: number;
};
export type ArrayPaginatorData<T> = Omit<
Required<ArrayPaginatorSettings<T>>,
'array'
>
& {
pageTotal: number;
page: T[];
};
export declare class ArrayPaginator<T> {
get data(): ArrayPaginatorData<T>;
constructor(settings?: ArrayPaginatorSettings<T>);
set(settings?: ArrayPaginatorSettings<T>): void;
}
// Get an instance:
const paginator = new ArrayPaginator({
array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
pageLength: 5
});
console.log(paginator.data);
/*****
{
pageLength: 5
pageNumber: 1
pageTotal: 2
page: [1,2,3,4,5]
}
*****/
paginator.set({pageLength: 4});
console.log(paginator.data);
/*****
{
pageLength: 4
pageNumber: 1
pageTotal: 3
page: [1,2,3,4]
}
*****/
paginator.set({pageNumber: 2});
console.log(paginator.data);
/*****
{
pageLength: 4
pageNumber: 2
pageTotal: 3
page: [5,6,7,8]
}
*****/
paginator.set({pageLength: 20, pageNumber: 1});
console.log(paginator.data);
/*****
{
pageLength: 20
pageNumber: 1
pageTotal: 1
page: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
}
*****/
// Since the total array length is only 10, trying to get a second page results in error:
paginator.set({pageNumber: 2});
// 'Error: The requested page does not exist'
npm i @writetome51/array-paginator
import {ArrayPaginator} from '@writetome51/array-paginator';