Skip to content

Instantly share code, notes, and snippets.

@nash403
Last active March 23, 2017 13:35
Show Gist options
  • Save nash403/06183a82ee08a4f4a84ae11047be50a5 to your computer and use it in GitHub Desktop.
Save nash403/06183a82ee08a4f4a84ae11047be50a5 to your computer and use it in GitHub Desktop.
Simple Pager structure in TypeScript
import { modulo } from "./utils";
export class Pager {
next:number = 0;
previous:number = 0;
constructor(public current:number = 0, public length:number = 0, noModulo:boolean = false) {
this.setNeighbours(noModulo);
}
/**
* Increase current value
* @param noModulo boolean that tells if the pager is circular
*/
goNext(noModulo:boolean = false) {
if (noModulo) {
if (!this.isLast()) {
this.setCurrent(this.current +1,noModulo);
}
} else {
this.setCurrent(this.current +1,noModulo);
}
}
/**
* Decrease current value
* @param noModulo boolean that tells if the pager is circular
*/
goPrevious(noModulo:boolean = false) {
if (noModulo) {
if (!this.isFirst()) {
this.setCurrent(this.current -1,noModulo);
}
} else {
this.setCurrent(this.current -1,noModulo);
}
}
isLast(): boolean {
return this.length > 0 ? this.current === this.length - 1 : true;
}
isFirst(): boolean {
return this.length > 0 ? this.current === 0 : true;
}
/**
* Set current value
* @param value
* @param noModulo boolean that tells if the pager is circular
*/
setCurrent(value:number, noModulo:boolean = false) {
if (noModulo) {
if (value >= 0 && value < this.length) {
this.current = value;
this.setNeighbours(noModulo);
}
} else {
this.current = modulo(value,this.length);
this.setNeighbours(noModulo);
}
}
/**
* Sets previous and next properties in compliance with current value
* @param noModulo boolean that tells if the pager is circular
*/
setNeighbours(noModulo:boolean = false) {
if (this.length <= 0) return;
if (noModulo) {
this.previous = this.current <= 0 ? 0 : this.current-1;
this.next = this.current >= this.length-1 ? this.length-1 : this.current +1;
} else {
this.previous = modulo(this.current -1, this.length);
this.next = modulo(this.current +1, this.length);
}
}
setLength(value:number, noModulo:boolean = false) {
if (value >= 0) this.length = value;
this.setNeighbours(noModulo);
}
}
/**
* Returns a value always between 0 and size - 1.
* @param a current index
* @param b size
*/
export function modulo(a, b) { return (+a % (b = +b) + b) % b; };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment