PageRenderTime 122ms CodeModel.GetById 80ms app.highlight 7ms RepoModel.GetById 34ms app.codeStats 0ms

/ucengine/src/helpers/uce_paginate.erl

http://github.com/AF83/ucengine
Erlang | 65 lines | 41 code | 7 blank | 17 comment | 0 complexity | dc31bb489fdf44e47fa804a30c2f9175 MD5 | raw file
 1%%
 2%%  U.C.Engine - Unified Collaboration Engine
 3%%  Copyright (C) 2011 af83
 4%%
 5%%  This program is free software: you can redistribute it and/or modify
 6%%  it under the terms of the GNU Affero General Public License as published by
 7%%  the Free Software Foundation, either version 3 of the License, or
 8%%  (at your option) any later version.
 9%%
10%%  This program is distributed in the hope that it will be useful,
11%%  but WITHOUT ANY WARRANTY; without even the implied warranty of
12%%  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13%%  GNU Affero General Public License for more details.
14%%
15%%  You should have received a copy of the GNU Affero General Public License
16%%  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17%%
18-module(uce_paginate).
19
20-export([index/3, sort/2, paginate/3]).
21
22index(Count, Index, Page) ->
23    case Count of
24        infinity ->
25            Index;
26        _ ->
27            (Count * (Page - 1)) + Index
28    end.
29
30sort(List, Order) ->
31    case Order of
32        asc ->
33            List;
34        desc ->
35            lists:reverse(List)
36    end.
37
38paginate(List, 0, infinity) ->
39    List;
40paginate(List, Start, Count) ->
41    Max = case Count of
42              infinity ->
43                  length(List);
44              _ ->
45                  Count
46          end,
47    if
48        Start > length(List) ->
49            [];
50        true ->
51            lists:sublist(List, Start + 1, Max)
52    end.
53
54-ifdef(TEST).
55-include_lib("eunit/include/eunit.hrl").
56
57paginate_test() ->
58    List = lists:seq(0, 12),
59    ?assertEqual(lists:seq(0, 9), paginate(List, 0, 10)),
60    ?assertEqual(lists:seq(0, 4), paginate(List, 0, 5)),
61    ?assertEqual(lists:seq(2, 11), paginate(List, 2, 10)),
62    ?assertEqual(lists:seq(5, 9), paginate(List, 5, 5)),
63    ?assertEqual(lists:seq(0, 12), paginate(List, 0, infinity)).
64
65-endif.