Skip to content

Instantly share code, notes, and snippets.

@automagisch
Last active October 31, 2019 13:31
Show Gist options
  • Save automagisch/4b1093f05fb24d62986692eeb17efa1a to your computer and use it in GitHub Desktop.
Save automagisch/4b1093f05fb24d62986692eeb17efa1a to your computer and use it in GitHub Desktop.
chunkify.js
/**
* const data = [...new Array(10000)]; // some huge array, browser compensates rendering because of size
* const pages = chunk(data, 200); // create pages from huge array
* pages.size; // size of the results per page
* pages.index; // current page index
* pages.data; // complete data set
* pages.chunks; // data set in chunks
* pages.get(0); // returns {pages.size} results at index [0-{pages.chunks.length}]
* pages.next(); // increments index and returns the result index page
* pages.prev(); // decrements index and returns the result index page
* pages.nav(); // returns html string with pages, arrows and state string
* pages.state(); // returns state string ('showing {from} to {to} in {total} entries.')
*/
/**
* @function
* @param {Array}
* @description Quickly paginatify an array dataset.
* @return {Object}
*/
function chunk(data=[], size=100) {
const chunks = [];
for(let i = 0; i < data.length; i+=size) {
chunks.push(data.slice(i, i+size));
}
return {
data,
size,
chunks,
index: 0,
// returns chunk fragment at index [index]
get(index=0) {
this.index = parseInt(index);
if(this.index > this.chunks.length)
this.index = this.chunks.length-1;
if(this.index < 0)
this.index = 0;
if(this.index > this.chunks.length) {
return this.get(this.chunks.length-1);
} else if(this.index < 0) {
return this.get(0);
} else {
return this.chunks[index];
}
},
// increments index and returns result set at [index]
next() {
if(this.index+1 > this.chunks.length-1) {
this.index = this.chunks.length-1;
} else {
this.index++;
}
return this.get(this.index);
},
// decrements index and returns result set at [index]
prev() {
if(this.index-1 < 0) {
this.index = 0;
} else {
this.index--;
}
return this.get(this.index);
},
// exposes default layout for pagination
nav() {
return `
<nav>
<p>${this.state()}</p>
<ul>
<li><a href="chunk:prev"><i>prev</i></a></li>
${this.chunks.map((c,i) => `<li><a ${!i ? "class='active'" : '' } href="chunk:${i}">${i+1}</a></li>`).join('')}
<li><a href="chunk:next"><i>next</i></a></li>
</ul>
</nav>
`;
},
// returns a string that displays which chunk is being observed
// e.g: 'Showing 101 to 200 in 7452 entries'
state() {
const from = (this.index * this.size)+1;
const to = (() => {
let est = (from + this.size)-1;
if(est > this.data.length) est = this.data.length;
return est;
})();
return `Showing ${from} to ${to} in ${this.data.length} entries.`;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment