Last active
November 18, 2022 00:05
-
-
Save gabrielh-silvestre/968f9a3a0fa53dab4107a0c9a27c0bb9 to your computer and use it in GitHub Desktop.
Generic filter for multiples conditions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const FILTERS_LOGIC = { | |
// Logic to filter | |
}; | |
const recursive = (apiArray, filtersArray) => ( | |
apiArray.reduce((acc, crv) => filteredData(acc, filtersArray), [...apiArray])); | |
const filteredData = (apiArray, filtersArray) => ( | |
apiArray.filter((item) => | |
filtersArray.every((filterObj) => | |
FILTERS_LOGIC[filterObj.access](item[filterObj.keyComparison], filterObj.valueToCompare) | |
) | |
)); | |
// EXAMPLE | |
const FILTER_COMPARISON = { | |
'maior que': (el1, el2) => Number(el1) > Number(el2), | |
'menor que': (el1, el2) => Number(el1) < Number(el2), | |
'igual a': (el1, el2) => Number(el1) === Number(el2), | |
'': () => false, | |
}; | |
const recursive = (apiArray, filtersArray) => | |
apiArray.reduce((acc, crv) => filteredData(acc, filtersArray), [...apiArray]); | |
const filteredData = (apiArray, filtersArray) =>( | |
apiArray.filter((item) => | |
filtersArray.every(({ column, comparison, value }) => | |
FILTER_COMPARISON[comparison](item[column], value) | |
) | |
)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment