PageRenderTime 27ms CodeModel.GetById 21ms RepoModel.GetById 1ms 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. -export([index/3, sort/2, paginate/3]).
  20. index(Count, Index, Page) ->
  21. case Count of
  22. infinity ->
  23. Index;
  24. _ ->
  25. (Count * (Page - 1)) + Index
  26. end.
  27. sort(List, Order) ->
  28. case Order of
  29. asc ->
  30. List;
  31. desc ->
  32. lists:reverse(List)
  33. end.
  34. paginate(List, 0, infinity) ->
  35. List;
  36. paginate(List, Start, Count) ->
  37. Max = case Count of
  38. infinity ->
  39. length(List);
  40. _ ->
  41. Count
  42. end,
  43. if
  44. Start > length(List) ->
  45. [];
  46. true ->
  47. lists:sublist(List, Start + 1, Max)
  48. end.
  49. -ifdef(TEST).
  50. -include_lib("eunit/include/eunit.hrl").
  51. paginate_test() ->
  52. List = lists:seq(0, 12),
  53. ?assertEqual(lists:seq(0, 9), paginate(List, 0, 10)),
  54. ?assertEqual(lists:seq(0, 4), paginate(List, 0, 5)),
  55. ?assertEqual(lists:seq(2, 11), paginate(List, 2, 10)),
  56. ?assertEqual(lists:seq(5, 9), paginate(List, 5, 5)),
  57. ?assertEqual(lists:seq(0, 12), paginate(List, 0, infinity)).
  58. -endif.