ha-frontend/src/components/data-table/sort_filter_worker.ts

78 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-05-18 16:51:46 +02:00
// To use comlink under ES5
import "proxy-polyfill";
import { expose } from "comlink";
import type {
DataTableSortColumnData,
DataTableRowData,
SortingDirection,
2020-05-19 13:59:16 +02:00
SortableColumnContainer,
} from "./ha-data-table";
2020-05-18 16:51:46 +02:00
const filterData = (
data: DataTableRowData[],
2020-05-18 16:51:46 +02:00
columns: SortableColumnContainer,
filter: string
2020-05-19 13:59:16 +02:00
) => {
filter = filter.toUpperCase();
return data.filter((row) => {
return Object.entries(columns).some((columnEntry) => {
const [key, column] = columnEntry;
if (column.filterable) {
if (
(column.filterKey ? row[key][column.filterKey] : row[key])
.toUpperCase()
.includes(filter)
) {
return true;
}
}
return false;
});
});
2020-05-19 13:59:16 +02:00
};
2020-05-18 16:51:46 +02:00
const sortData = (
data: DataTableRowData[],
2020-05-18 16:51:46 +02:00
column: DataTableSortColumnData,
direction: SortingDirection,
sortColumn: string
) =>
data.sort((a, b) => {
let sort = 1;
if (direction === "desc") {
sort = -1;
}
let valA = column.filterKey
? a[sortColumn][column.filterKey]
: a[sortColumn];
let valB = column.filterKey
? b[sortColumn][column.filterKey]
: b[sortColumn];
if (typeof valA === "string") {
valA = valA.toUpperCase();
}
if (typeof valB === "string") {
valB = valB.toUpperCase();
}
if (valA < valB) {
return sort * -1;
}
if (valA > valB) {
return sort * 1;
}
return 0;
});
2020-05-18 16:51:46 +02:00
2020-05-23 08:05:47 +02:00
const api = {
2020-05-19 13:59:16 +02:00
filterData,
sortData,
2020-05-18 16:51:46 +02:00
};
2020-05-23 08:05:47 +02:00
export type api = typeof api;
2020-05-18 16:51:46 +02:00
expose(api);