2019-07-09 10:35:24 +02:00
|
|
|
import { createSelector } from 'reselect';
|
|
|
|
import differenceInMilliseconds from 'date-fns/difference_in_milliseconds';
|
|
|
|
import find from 'lodash/find';
|
|
|
|
import orderBy from 'lodash/orderBy';
|
|
|
|
import { DIRECTION } from '../actions/sorting';
|
|
|
|
|
|
|
|
const getCollections = state => state.collections;
|
|
|
|
const getField = state => state.sorting.field;
|
|
|
|
const getDirection = state => state.sorting.direction;
|
2019-11-10 21:39:22 +01:00
|
|
|
const getSearchTerm = state => state.search.collectionSearchTerm;
|
2019-07-09 10:35:24 +02:00
|
|
|
|
2019-11-10 21:39:22 +01:00
|
|
|
const getFilteredCollections = createSelector(
|
2019-07-09 10:35:24 +02:00
|
|
|
getCollections,
|
2019-11-10 21:39:22 +01:00
|
|
|
getSearchTerm,
|
|
|
|
(collections, search) => {
|
|
|
|
if (search) {
|
|
|
|
const searchStrings = collections.map((collection) => {
|
|
|
|
const smallCollection = {
|
|
|
|
name: collection.name
|
|
|
|
};
|
|
|
|
return { ...collection, searchString: Object.values(smallCollection).join(' ').toLowerCase() };
|
|
|
|
});
|
|
|
|
return searchStrings.filter(collection => collection.searchString.includes(search.toLowerCase()));
|
|
|
|
}
|
|
|
|
return collections;
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
|
|
|
|
const getSortedCollections = createSelector(
|
|
|
|
getFilteredCollections,
|
2019-07-09 10:35:24 +02:00
|
|
|
getField,
|
|
|
|
getDirection,
|
|
|
|
(collections, field, direction) => {
|
|
|
|
if (field === 'name') {
|
|
|
|
if (direction === DIRECTION.DESC) {
|
|
|
|
return orderBy(collections, 'name', 'desc');
|
|
|
|
}
|
|
|
|
return orderBy(collections, 'name', 'asc');
|
2020-06-20 10:51:51 +02:00
|
|
|
} else if (field === 'numItems') {
|
|
|
|
if (direction === DIRECTION.DESC) {
|
|
|
|
return orderBy(collections, 'items.length', 'desc');
|
|
|
|
}
|
|
|
|
return orderBy(collections, 'items.length', 'asc');
|
2019-07-09 10:35:24 +02:00
|
|
|
}
|
|
|
|
const sortedCollections = [...collections].sort((a, b) => {
|
|
|
|
const result =
|
|
|
|
direction === DIRECTION.ASC
|
|
|
|
? differenceInMilliseconds(new Date(a[field]), new Date(b[field]))
|
|
|
|
: differenceInMilliseconds(new Date(b[field]), new Date(a[field]));
|
|
|
|
return result;
|
|
|
|
});
|
|
|
|
return sortedCollections;
|
|
|
|
}
|
|
|
|
);
|
|
|
|
|
|
|
|
export function getCollection(state, id) {
|
|
|
|
return find(getCollections(state), { id });
|
|
|
|
}
|
|
|
|
|
|
|
|
export default getSortedCollections;
|