From 482a50113a3348eda90125d061edad7a1670ee2d Mon Sep 17 00:00:00 2001 From: Tom Jackson Date: Tue, 15 Jan 2013 20:02:16 -0800 Subject: [PATCH] contains() Summary: TSIA Test Plan: Unit tests Reviewed By: tulloch@fb.com FB internal diff: D680177 --- folly/experimental/Gen-inl.h | 26 ++++++++++++++++++++++++++ folly/experimental/Gen.h | 11 ++++++++++- folly/experimental/test/GenTest.cpp | 19 +++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) diff --git a/folly/experimental/Gen-inl.h b/folly/experimental/Gen-inl.h index bde69792..6937fbb6 100644 --- a/folly/experimental/Gen-inl.h +++ b/folly/experimental/Gen-inl.h @@ -1131,6 +1131,32 @@ class Sum : public Operator { } }; +/** + * 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 Contains : public Operator> { + Needle needle_; + public: + explicit Contains(Needle needle) + : needle_(std::move(needle)) + {} + + template::type> + bool compose(const GenImpl& source) const { + return !(source | [this](Value value) { + return !(needle_ == std::forward(value)); + }); + } +}; + /** * Min - For a value which minimizes a key, where the key is determined by a * given selector, and compared by given comparer. diff --git a/folly/experimental/Gen.h b/folly/experimental/Gen.h index 4583af49..8d23e1ab 100644 --- a/folly/experimental/Gen.h +++ b/folly/experimental/Gen.h @@ -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 GeneratorBuilder {}; +template +class Contains; + } /** @@ -430,6 +433,12 @@ Append appendTo(Collection& collection) { return Append(&collection); } +template::type>> +Contains contains(Needle&& needle) { + return Contains(std::forward(needle)); +} + }} // folly::gen #include "folly/experimental/Gen-inl.h" diff --git a/folly/experimental/test/GenTest.cpp b/folly/experimental/test/GenTest.cpp index de2e4afb..a4d1a77e 100644 --- a/folly/experimental/test/GenTest.cpp +++ b/folly/experimental/test/GenTest.cpp @@ -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 gen, const char* needle + EXPECT_TRUE(gen | contains("49")); + } +} + TEST(Gen, Take) { auto expected = vector{1, 4, 9, 16}; auto actual = -- 2.34.1