Permalink
Browse files

contains()

Summary: TSIA

Test Plan: Unit tests

Reviewed By: tulloch@fb.com

FB internal diff: D680177
  • Loading branch information...
1 parent a0d036e commit 482a50113a3348eda90125d061edad7a1670ee2d Tom Jackson committed with jdelong Jan 16, 2013
Showing with 55 additions and 1 deletion.
  1. +26 −0 folly/experimental/Gen-inl.h
  2. +10 −1 folly/experimental/Gen.h
  3. +19 −0 folly/experimental/test/GenTest.cpp
@@ -1131,6 +1131,32 @@ class Sum : public Operator<Sum> {
}
};
+/**
+ * Contains - For testing whether a value matching the given value is contained
+ * in a sequence.
+ *
+ * This type should be used through the 'contains' helper method, like:
+ *
+ * bool contained = seq(1, 10) | map(square) | contains(49);
+ */
+template<class Needle>
+class Contains : public Operator<Contains<Needle>> {
+ Needle needle_;
+ public:
+ explicit Contains(Needle needle)
+ : needle_(std::move(needle))
+ {}
+
+ template<class Source,
+ class Value,
+ class StorageType = typename std::decay<Value>::type>
+ bool compose(const GenImpl<Value, Source>& source) const {
+ return !(source | [this](Value value) {
+ return !(needle_ == std::forward<Value>(value));
+ });
+ }
+};
+
/**
* Min - For a value which minimizes a key, where the key is determined by a
* given selector, and compared by given comparer.
View
@@ -1,5 +1,5 @@
/*
- * Copyright 2012 Facebook, Inc.
+ * Copyright 2013 Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -245,6 +245,9 @@ class Append;
template<class Value>
class GeneratorBuilder {};
+template<class Needle>
+class Contains;
+
}
/**
@@ -430,6 +433,12 @@ Append appendTo(Collection& collection) {
return Append(&collection);
}
+template<class Needle,
+ class Contains = detail::Contains<typename std::decay<Needle>::type>>
+Contains contains(Needle&& needle) {
+ return Contains(std::forward<Needle>(needle));
+}
+
}} // folly::gen
#include "folly/experimental/Gen-inl.h"
@@ -144,6 +144,25 @@ TEST(Gen, Filter) {
EXPECT_EQ(expected, actual);
}
+TEST(Gen, Contains) {
+ {
+ auto gen =
+ seq(1, 9)
+ | map(square);
+ EXPECT_TRUE(gen | contains(49));
+ EXPECT_FALSE(gen | contains(50));
+ }
+ {
+ auto gen =
+ seq(1) // infinite, to prove laziness
+ | map(square)
+ | eachTo<std::string>();
+
+ // std::string gen, const char* needle
+ EXPECT_TRUE(gen | contains("49"));
+ }
+}
+
TEST(Gen, Take) {
auto expected = vector<int>{1, 4, 9, 16};
auto actual =

0 comments on commit 482a501

Please sign in to comment.