summaryrefslogtreecommitdiff
path: root/src/components/Mixins/TableFilterMixin.js
blob: 7cb7007d0c964344d25b3d58c17a91853b125c45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { includes } from 'lodash';

const TableFilterMixin = {
  methods: {
    getFilteredTableData(tableData = [], filters = []) {
      const filterItems = filters.reduce((arr, filter) => {
        return [...arr, ...filter.values];
      }, []);
      // If no filters are active, then return all table data
      if (filterItems.length === 0) return tableData;

      // Check if row property value is included in list of
      // active filters
      return tableData.filter(row => {
        let returnRow = false;
        for (const { key, values } of filters) {
          const rowProperty = row[key];
          if (rowProperty && includes(values, rowProperty)) {
            returnRow = true;
            break;
          }
        }
        return returnRow;
      });
    },
    getFilteredTableDataByDate(
      tableData = [],
      startDate,
      endDate,
      propertyKey = 'date'
    ) {
      if (!startDate && !endDate) return tableData;
      const startDateInMs = startDate ? startDate.getTime() : 0;
      const endDateInMs = endDate
        ? endDate.getTime()
        : Number.POSITIVE_INFINITY;
      return tableData.filter(row => {
        const date = row[propertyKey];
        if (!(date instanceof Date)) return;

        const dateInMs = date.getTime();
        if (dateInMs >= startDateInMs && dateInMs <= endDateInMs) return row;
      });
    }
  }
};

export default TableFilterMixin;