@trap_stevo/legendarybuilderpronodejs-utilities
Version:
The legendary computational utility API that makes your application a legendary application. ~ Created by Steven Compton
111 lines (84 loc) • 2.7 kB
JavaScript
class ContainerArray
{
constructor(pageSize = 100)
{
this.pageSize = pageSize;
this.pages = [];
this.totalItems = 0;
}
add(item)
{
if (this.pages.length === 0 || this.pages[this.pages.length - 1].length === this.pageSize)
{
this.pages.push([]);
}
this.pages[this.pages.length - 1].push(item);
this.totalItems++;
}
getItem(index)
{
if (index < 0 || index >= this.totalItems)
{
return undefined;
}
const pageIndex = Math.floor(index / this.pageSize);
const itemIndex = index % this.pageSize;
return this.pages[pageIndex] ? this.pages[pageIndex][itemIndex] : undefined;
}
reverseForEachPage(callback)
{
let count = 0;
for (let pageIndex = 0; pageIndex < this.pages.length; pageIndex++)
{
const page = this.pages[pageIndex];
for (let i = page.length - 1; i >= 0; i--)
{
callback(page[i], i, pageIndex, count++);
}
}
}
reverseForEach(callback)
{
let count = this.totalItems - 1;
for (let pageIndex = this.pages.length - 1; pageIndex >= 0; pageIndex--)
{
const page = this.pages[pageIndex];
for (let i = page.length - 1; i >= 0; i--)
{
callback(page[i], i, pageIndex, count--);
}
}
}
getPaginatedData(page, limit)
{
const startIndex = page * limit;
const endIndex = startIndex + limit;
const result = [];
for (let i = startIndex; i < endIndex && i < this.totalItems; i++)
{
result.push(this.getItem(i));
}
return result;
}
forEach(callback)
{
let count = 0;
for (let pageIndex = 0; pageIndex < this.pages.length; pageIndex++)
{
const page = this.pages[pageIndex];
for (let i = 0; i < page.length; i++)
{
callback(page[i], count++);
}
}
}
get totalPages()
{
return this.pages.length;
}
get length()
{
return this.totalItems;
}
}
module.exports = ContainerArray;