You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

randomDataReducer.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import createReducer from '../../utils/createReducer';
  2. import {
  3. LOAD_DATA,
  4. UPDATE_PAGE,
  5. UPDATE_ITEMS_PER_PAGE,
  6. UPDATE_FILTER,
  7. UPDATE_SORT,
  8. } from '../../actions/randomData/randomDataActionConstants.js';
  9. import generate from '../../../util/helpers/randomData';
  10. const initialState = {
  11. items: [],
  12. filteredItems: [],
  13. count: 0,
  14. page: 0,
  15. itemsPerPage: 12,
  16. filter: '',
  17. sort: '',
  18. };
  19. export default createReducer(
  20. {
  21. [LOAD_DATA]: loadRandomData,
  22. [UPDATE_PAGE]: updatePage,
  23. [UPDATE_ITEMS_PER_PAGE]: updateItemsPerPage,
  24. [UPDATE_FILTER]: updateFilter,
  25. [UPDATE_SORT]: updateSort,
  26. },
  27. initialState
  28. );
  29. function loadRandomData(state, action) {
  30. const count = action.payload;
  31. const items = generate(count);
  32. return {
  33. ...state,
  34. items,
  35. filteredItems: items,
  36. count: items.length,
  37. };
  38. }
  39. function updatePage(state, action) {
  40. const page = action.payload;
  41. return {
  42. ...state,
  43. page,
  44. };
  45. }
  46. function updateItemsPerPage(state, action) {
  47. const itemsPerPage = action.payload;
  48. return {
  49. ...state,
  50. itemsPerPage,
  51. };
  52. }
  53. function updateFilter(state, action) {
  54. const filter = action.payload;
  55. const filteredItems = filter
  56. ? state.items.filter((item) => item.name.toLowerCase().includes(filter.toLowerCase())) : state.items;
  57. return {
  58. ...state,
  59. filter,
  60. filteredItems,
  61. count: filteredItems.length,
  62. };
  63. }
  64. function updateSort(state, action) {
  65. const sort = action.payload;
  66. const [field, direction] = sort.split('-');
  67. const sortDirection = direction === 'asc' ? 1 : -1;
  68. const dataItems = state.filteredItems.length
  69. ? state.filteredItems
  70. : state.items;
  71. const sorted = dataItems.sort((a, b) => {
  72. if (a[field] > b[field]) {
  73. return sortDirection;
  74. }
  75. if (b[field] > a[field]) {
  76. return sortDirection * -1;
  77. }
  78. return 0;
  79. });
  80. const filteredItems = state.filteredItems.length
  81. ? sorted
  82. : state.filteredItems;
  83. return {
  84. ...state,
  85. sort,
  86. filteredItems,
  87. };
  88. }