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: 'settings.tags',
  values: ['blank', 'hello']
}]

function cleanForComparison(value, type) {
  if (type === 'date') {
    return value
  }

  return value.toString().toLowerCase().trim()
}

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

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

  // @HC NOTE: Mapping moved to searchBy() function on actual Studio code

  // Use _.every here to make sure every filter condition in the activeFilters array is passed
  return _.every(activeFilters, (filter) => {
    let fieldValue = _.get(record, filter.key)

    // If no value or no filed value to check against
    // assumes is to show
    if (!filter.values.length || !fieldValue) {
      return true
    }

    // Convert to string and lowercase for comparison
    const filterValues = _.map(filter.values, (value) => {
      return cleanForComparison(value, filter.type)
    })

    // Convert to string and lowercase for comparison
    fieldValue = !Array.isArray(fieldValue)
    	? cleanForComparison(fieldValue, filter.type)
      : fieldValue

    // If filter type is date
    if (filter.type === 'date') {
      if (typeof moment.fn[filter.logic] !== 'function') {
        return
      }

      // Use logic property to run the possible comparisons supported by moment.js
      return moment.fn[filter.logic].apply(moment(fieldValue), filterValues)
    }
    
    if (Array.isArray(fieldValue)) {
      return _.some(fieldValue, (value) => {
        return filterValues.indexOf(cleanForComparison(value, filter.type)) > -1
      })
    }
    
    return filterValues.indexOf(fieldValue) > -1
    
  })
}

const match = recordMatchesFilter({
  activeFilters: activeFilters,
  record: screens[0]
})

console.log(match)