Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Final encoded email filter
object final_encoded_email_filter {
final case class Address(emailAddress: String)
final case class Email(sender: Address, to: List[Address], subject: String, body: String)
case class EmailFilter(run: Email => Boolean) { self =>
def &&(that: EmailFilter): EmailFilter = EmailFilter(email => self.run(email) && that.run(email))
def ||(that: EmailFilter): EmailFilter = EmailFilter(email => self.run(email) || that.run(email))
def negate : EmailFilter = EmailFilter(email => !self.run(email))
}
object EmailFilter {
val always: EmailFilter = EmailFilter(_ => true)
val never: EmailFilter = always.negate
def senderIs(sender: Address): EmailFilter = EmailFilter(email => email.sender == sender)
def senderIsNot(sender: Address): EmailFilter = senderIs(sender).negate
def recipientIs(recipient: Address): EmailFilter = EmailFilter(email => email.to.contains(recipient))
def recipientIsNot(recipient: Address): EmailFilter = recipientIs(recipient).negate
def senderIn(senders: Set[Address]): EmailFilter = senders.foldLeft(never)(_ || senderIs(_))
def recipientIn(recipients: Set[Address]): EmailFilter = recipients.foldLeft(never)(_ || recipientIs(_))
def bodyContains(phrase: String): EmailFilter = EmailFilter(email => email.body.contains(phrase))
def bodyDoesNotContain(phrase: String): EmailFilter = bodyContains(phrase).negate
}
val filter: EmailFilter = EmailFilter.senderIsNot(Address("me@gmail.com")) && EmailFilter.bodyContains("Unsubscribe")
val emails: List[Email] = List(Email(Address("info@someretailer.com"), List(Address("me@gmail.com")), "Promotion", "10% off. Unsubscribe"))
val newsletters: List[Email] = emails.filter(filter.run)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment