check filters

by Hugo Carneiro

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

JavaScript

const NEW_LAYOUT_DAYS = 21

const screens = [{
  id: 1,
  name: 'Blank',
  settings: {
    tags: ['blank', 'new']
  },
  createdAt: '2021-11-29T15:15:20.130Z'
}]

const activeFilters = [{
  key: 'createdAt',
  value: [moment().utc().subtract(NEW_LAYOUT_DAYS, 'days').format(), moment().utc().format()],
  type: 'date',
  logic: 'isBetween'
}]

function recordMatchesFilter(options) {
  options = options || {}

  let activeFilters = options.activeFilters || []
  const record = options.record || {}

	// @NOTE: Use _.every here to make sure every filter condition in the activeFilters array is passed
  return _.every(activeFilters, (filter) => {
    const fieldValue = _.get(record, filter.key)
    
    // If no value or no filed value to check against
    // assumes is to show
    if (!filter.value.length || !fieldValue) {
      return true
    }
    
    // If filter type is date
    // Check between two dates
    if (filter.type === 'date') {
    	if (typeof moment.fn[filter.logic] !== 'function') {
      	return
      }

    	// @Note: In addition to type: 'date', if you add logic: 'isAfter' (the moment comparison function name) then you can support lots more date comparisons
      // e.g. return moment(fieldValue)[filter.logic].apply(null, filter.value);
      // You'll want to check first that moment.fn[filter.logic] is a valid function
      return moment(fieldValue)[filter.logic].apply(null, filter.value);
    }

    return _.some(filter.value, (value) => {
    	// @NOTE: This shouldn't need to be done on every record
      // Look carefully through every single line and determine whether they need to be done on every single loop if you had 1 million entries
    	value = value.toString().toLowerCase()

      // If the field value is an array
      if (Array.isArray(fieldValue)) {
      	return _.some(fieldValue, (valueItem) => {
        	return valueItem.toString().toLowerCase() === value
        })
      }

			// If the fied value is anything else
      return...