Skip to content

writetome51/array-paginator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

71 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ArrayPaginator<T>

A TypeScript class for paginating an array.

API

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;
}

Usage Examples

// 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'

Installation

npm i  @writetome51/array-paginator

Loading

import {ArrayPaginator} from '@writetome51/array-paginator';

License

MIT