Added default value for filter's predicate argument
authorJoe Richey <jrichey@fb.com>
Thu, 9 Jul 2015 21:48:17 +0000 (14:48 -0700)
committerSara Golemon <sgolemon@fb.com>
Thu, 9 Jul 2015 22:32:56 +0000 (15:32 -0700)
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

folly/gen/Base-inl.h
folly/gen/Base.h
folly/gen/test/BaseTest.cpp

index ade7b5d898aa49cfb56b138290ae55eeda9ed0b0..3827fdf4216998187523dd8baaa64eae9b538fcd 100644 (file)
@@ -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>> {
index 8a52eb2981db4461b03fd37853a7eca10cdbc63c..322b895e5f853860c421b939c6861b3fced4dfe5 100644 (file)
@@ -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));
 }
index 62818f0d9f6c57aae958c7c95077522d9dd9202c..c25f40c7e2049b6d9d127e30a80f4c0fc37b4476 100644 (file)
@@ -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 =