I need a little help with this filter function <ht...
# codereview
o
I need a little help with this filter function https://pastebin.com/i6V7L5xq
a
you could build a list of small filter functions and then
fold
over the list of filters and the car list
Copy code
if(selectedCarModelId != null)
    filters.add { selectedCarModelId == it.model_id }

if(selectedCarSubModelId != null)
    filters.add { selectedCarSubModelId == it.submodel_id }

filters.fold(carList) { cars, filter -> cars.filter(::filter) }
o
hm
let me try
my
filters
value would be
mutableListOf({})
?
a
mutableListOf<(YourCarType) -> Boolean>()
o
oh
what is that a type of?
that itself is a lambda
ok
a
it is a list of functions that take your
Car
and returns a
Boolean
o
yes
a
fold
then just takes the original list of cars and applies every
filter
to your list and returns the filtered list of cars
k
another option is to have the null checks embedded in the filter condition
Copy code
carListings.filter {
        (selectedCarModelId == null || selectedCarModelId == it.model_id)
        && (selectedCarSubModelId == null || selectedCarSubModelId == it.submodel_id)
        && (selectedCarTrimId == null || selectedCarTrimId == it.trim_id)
        && (fromYearSelected == null || fromYearSelected < it.year)
        && (toYearSelected == null || toYearSelected > it.year)
        && it.mileage < mileageValue
        && it.price < budgetValue
    }
o
the fold returned nothing to me
it didn’t fail, but nothing was returned by the filter
a
show me the code you have right now
o
@kristofdho’s one works fine
see I didnt know you can do that in the if
k
you should also reduce the scope of the try block, it's way bigger than it needs to be
o
hm
well budget is still used
Im not sure what you mean
k
Copy code
var budgetValue = try {
    nf.parse(budgetValueTV.text.toString()).toInt()
} catch (e: ParseException) {
    Timber.d("Budget was never entered because in offline mode.")
    return emptyList()
}
you can use
budgetValue
after that
o
and then the actual filtering
k
yes
o
yea ok that makes sense
a
you swapped the last two filters. it was
it.price < budgetValue
and now its
budgetValue < it.price
. same for mileage
o
yes he did
ahhh
true, I did the same error in @kristofdho’s example now, and it also returned nothing
so both of these solutions should work, let me just try the fold solution again with the correct conditions
yes they work exactly the same
im not really sure how @kristofdho’s solution works though
k
short circuiting or conditions 😛
o
but @Andreas Sinz’s seems more elegant
what if I want to add more
it becomes a monstrosity
a
my solution just decouples the "determine which filters to apply" from the actual filtering, so it should be easier to understand what it does 😄