cheetah-framework
Version:
Cheetah Framework JS used in all our applications
110 lines (91 loc) • 2.43 kB
JavaScript
import config from '@cheetah/config'
function cleanText (str) {
return _.deburr(str).toLowerCase()
}
function clearPhone (phone) {
return phone.replace(/[^0-9]+/g, '')
}
function getFilterSeparatedValues (searchString, minSearchCharacters = 2, splitRegex = config.defaultInputSplitRegExp) {
return cleanText(searchString).split(splitRegex).filter(chunk => {
return chunk.length >= minSearchCharacters
})
}
function generateBackendCriteria (filterValues, properties) {
if (filterValues.length > 1) {
return _.map(properties, prop => {
return {
operator: 'and',
criteria: _.map(filterValues, filterValue => {
return {
field: prop.replace('.*.', '.'),
operator: 'like',
value: `%${filterValue}%`
}
})
}
})
}
const filterValue = _.first(filterValues)
return _.map(properties, prop => {
return {
field: prop.replace('.*.', '.'),
operator: 'like',
value: `%${filterValue}%`
}
})
}
/**
* @param {Object} item - model instance
* @param {Array} filterValues - separated filter values generate by getFilterSeparatedValues function
* @param {Array} filterableProps - item props we want to validate filter value matches
* @returns {Boolean}
*/
function validateItem (item, filterValues, filterableProps) {
let valid = false
_.each(filterableProps, prop => {
if (prop.indexOf('.*.') !== -1) {
_.each(_.seek(item, prop), value => {
valid |= isAllWordMatching(value, filterValues)
if (valid) {
return false
}
})
} else {
valid |= isAllWordMatching(_.get(item, prop), filterValues)
}
if (valid) {
return false
}
})
return valid
}
function isAllWordMatching (string, filterValues) {
const propValue = cleanText(string)
let valid = true
_.each(filterValues, filterValue => {
valid &= _.includes(propValue, filterValue)
})
return valid
}
function matchWith (string, queryString) {
const queries = getFilterSeparatedValues(queryString)
return isAllWordMatching(string, queries)
}
export default {
cleanText,
matchWith,
clearPhone,
isAllWordMatching,
validateItem,
generateBackendCriteria,
getFilterSeparatedValues
}
export {
cleanText,
matchWith,
clearPhone,
isAllWordMatching,
validateItem,
generateBackendCriteria,
getFilterSeparatedValues
}