import type { FilterType , ToggleType , ListType , ListItemSpecType } from './types' ; import values from 'lodash/values' ; import difference from 'lodash/difference' ; import intersection from 'lodash/intersection' ; export function applyFiltersToItem ( filters , item ) { return filters . every ( ( f ) => applyFilter ( f , item ) ) ; } export function applyFilter ( filter , item ) { if ( ! filter . enabled ) { return true ; } switch ( filter . type ) { case 'toggle' : return applyToggleFilter ( filter , item ) ; case 'list' : return applyListFilter ( filter , item ) ; default : return true ; } } export function applyToggleFilter ( filter , item ) { let itemValue = item [ filter . apply . key ] ; return filter . apply . trueEquivalent ? itemValue === filter . apply . trueEquivalent : Boolean ( itemValue ) ; } export function applyListFilter ( filter , item ) { let itemValue = item [ filter . apply . key ] ; let filterValue = filter . spec . selected ; switch ( filter . spec . mode ) { case 'OR' : return applyOrListFilter ( filterValue , itemValue ) ; case 'AND' : return applyAndListFilter ( filterValue , itemValue ) ; default : return true ; } } export function applyOrListFilter ( filterValue , itemValue ) { if ( ! Array . isArray ( itemValue ) ) { return filterValue . map ( ( f ) => f . title ) . includes ( itemValue ) ; } let valueToCheckAgainst = filterValue . map ( ( f ) => f . title . toString ( ) ) ; let intersectionValues = intersection ( valueToCheckAgainst , itemValue ) ; return intersectionValues . length !== 0 ; } export function applyAndListFilter ( filterValue , itemValue ) { if ( ! Array . isArray ( itemValue ) ) { itemValue = values ( itemValue ) ; } if ( ! itemValue . length ) { return false ; } let valueToCheckAgainst = filterValue . map ( ( f ) => f . title ) ; let differentItems = difference ( valueToCheckAgainst , itemValue ) ; return differentItems . length === 0 ; }