Created
September 8, 2016 22:45
-
-
Save DrMabuse23/1f2ff511823b5226c3edbd33c42a4eba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fake = () => { | |
let _data = []; | |
for (i = 0, l = 46; i < l; i++) { | |
let card = faker.helpers.userCard(); | |
card.id = (i + 1); | |
_data.push(card); | |
} | |
return _data; | |
} | |
const pager = (offset = 0, limit = 100) => { | |
return Rx.Observable.range(getOffset(offset), getLimit(offset, limit)); | |
} | |
const getOffset = (offset) => { | |
return offset > 0 ? offset : 0; | |
} | |
const getLimit = (offset, limit) => { | |
const sum = (Number(offset) + Number(limit)); | |
return sum < data.length ? limit : data.length - offset; | |
} | |
const getNext = (offset, limit) => { | |
let next = false; | |
if ((offset + limit) < data.length) { | |
next = { | |
limit: limit, | |
offset: getOffset(offset) + limit | |
} | |
} else if ((offset + limit) > data.length && offset < data.length) { | |
next = { | |
limit: getLimit(offset, limit), | |
offset: data.length - getLimit(offset, limit) | |
} | |
} | |
return next; | |
} | |
const getPrev = (offset, limit) => { | |
let prev = false; | |
if ((offset - limit) > 0) { | |
prev = { | |
limit: limit, | |
offset: getOffset(offset) - limit | |
} | |
} else if ((offset - limit) < 0 && offset > 0) { | |
prev = { | |
limit: limit, | |
offset: 0 | |
} | |
} | |
return prev; | |
} | |
const getLast = (offset, limit) => { | |
const rest = (data.length - offset) > limit; | |
if (rest) { | |
return getLast(offset + limit, limit); | |
} | |
if (offset + limit === data.length) { | |
return { | |
limit: limit, | |
offset: offset | |
}; | |
} | |
return getNext(offset, limit); | |
} | |
const data = fake(); | |
let limit = 3; | |
let offset = 30; | |
const view = []; | |
pager(offset, limit) | |
.filter((x) => { | |
return data[x - 1] !== undefined; | |
}) | |
.subscribe( | |
(x) => { | |
view.push(data[x - 1]); | |
}, | |
(e) => console.error(e), | |
() => { | |
console.log(view); | |
let _page = { | |
total: data.length, | |
items: view, | |
limit: limit, | |
offset: offset | |
}; | |
_page.last = getLast(offset, limit); | |
_page.next = getNext(offset, limit); | |
_page.prev = getPrev(offset, limit); | |
_page.totalPages = Math.ceil(data.length / limit); | |
_page.page = Math.ceil(offset/limit); | |
console.log(_page); | |
} | |
); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment