Last active
October 22, 2018 09:09
-
-
Save azami/4f39201621c9365bb4205a541366cb1e 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
import * as assert from "power-assert"; | |
import { getPagesToShow } from "../pagenation"; | |
describe("getPagesToShow", () => { | |
it("ページがmaxNumより少ない場合", () => { | |
assert.deepEqual(getPagesToShow(1, 3, 5), [1, 2, 3]); | |
}); | |
it("7ページ中1ページ目", () => { | |
assert.deepEqual(getPagesToShow(1, 7, 5), [1, 2, 3, 4, 5]); | |
}); | |
it("7ページ中2ページ目", () => { | |
assert.deepEqual(getPagesToShow(2, 7, 5), [1, 2, 3, 4, 5]); | |
}); | |
it("7ページ中3ページ目", () => { | |
assert.deepEqual(getPagesToShow(3, 7, 5), [1, 2, 3, 4, 5]); | |
}); | |
it("7ページ中4ページ目", () => { | |
assert.deepEqual(getPagesToShow(4, 7, 5), [2, 3, 4, 5, 6]); | |
}); | |
it("7ページ中5ページ目", () => { | |
assert.deepEqual(getPagesToShow(5, 7, 5), [3, 4, 5, 6, 7]); | |
}); | |
it("7ページ中6ページ目", () => { | |
assert.deepEqual(getPagesToShow(6, 7, 5), [3, 4, 5, 6, 7]); | |
}); | |
it("7ページ中7ページ目", () => { | |
assert.deepEqual(getPagesToShow(7, 7, 5), [3, 4, 5, 6, 7]); | |
}); | |
}); |
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
export const getPagesToShow = ( | |
currentPage: number, | |
maxPageCount: number, | |
maxNum = 5 | |
) => { | |
const allPages = [...Array(maxPageCount).keys()].map(x => x + 1); | |
const middle = Math.floor(maxNum / 2); | |
return currentPage - 1 <= middle | |
? allPages.slice(0, maxNum) | |
: allPages.length - currentPage > middle | |
? allPages.slice(currentPage - middle - 1, currentPage + middle) | |
: allPages.slice(allPages.length - maxNum, allPages.length); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment