Commit 91343de6 authored by Joe Richey's avatar Joe Richey Committed by Sara Golemon

Added default value for filter's predicate argument

Summary: After discussion with Tom about frozen files, we noticed that the use
case of filtering out somthing that looks like false (0, nullptr, folly::none)
is unnecessarily tedious. So folly::gen::filter now filters by the value of
the item by default.

Reviewed By: @ddrcoder

Differential Revision: D2220582
parent c78afbd2
......@@ -483,7 +483,6 @@ class Map : public Operator<Map<Predicate>> {
}
};
/**
* Filter - For filtering values from a source sequence by a predicate.
*
......@@ -493,6 +492,13 @@ class Map : public Operator<Map<Predicate>> {
* | filter([](const string& str) -> bool {
* return !str.empty();
* });
*
* Note that if no predicate is provided, the values are casted to bool and
* filtered based on that. So if pointers is a vector of pointers,
*
* auto nonNull = from(pointers) | filter();
*
* will give a vector of all the pointers != nullptr.
*/
template<class Predicate>
class Filter : public Operator<Filter<Predicate>> {
......
......@@ -614,8 +614,8 @@ Map field(FieldType Class::*field) {
return Map(Field(field));
}
template<class Predicate,
class Filter = detail::Filter<Predicate>>
template <class Predicate = Identity,
class Filter = detail::Filter<Predicate>>
Filter filter(Predicate pred = Predicate()) {
return Filter(std::move(pred));
}
......
......@@ -255,6 +255,40 @@ TEST(Gen, Filter) {
EXPECT_EQ(expected, actual);
}
TEST(Gen, FilterDefault) {
{
// Default filter should remove 0s
const auto expected = vector<int>{1, 1, 2, 3};
auto actual =
from({0, 1, 1, 0, 2, 3, 0})
| filter()
| as<vector>();
EXPECT_EQ(expected, actual);
}
{
// Default filter should remove nullptrs
int a = 5;
int b = 3;
int c = 0;
const auto expected = vector<int*>{&a, &b, &c};
auto actual =
from({(int*)nullptr, &a, &b, &c, (int*)nullptr})
| filter()
| as<vector>();
EXPECT_EQ(expected, actual);
}
{
// Default filter on Optionals should remove folly::null
const auto expected =
vector<Optional<int>>{Optional<int>(5), Optional<int>(0)};
const auto actual =
from({Optional<int>(5), Optional<int>(), Optional<int>(0)})
| filter()
| as<vector>();
EXPECT_EQ(expected, actual);
}
}
TEST(Gen, Contains) {
{
auto gen =
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment