Skip to content

Instantly share code, notes, and snippets.

View bijancn's full-sized avatar

Bijan Chokoufe Nejad bijancn

View GitHub Profile
{"lastUpload":"2020-10-16T15:12:58.640Z","extensionVersion":"v3.4.3"}
@bijancn
bijancn / Gzip.scala
Created November 13, 2018 13:28 — forked from owainlewis/Gzip.scala
Gzip Scala
import java.io.{ByteArrayOutputStream, ByteArrayInputStream}
import java.util.zip.{GZIPOutputStream, GZIPInputStream}
import scala.util.Try
object Gzip {
def compress(input: Array[Byte]): Array[Byte] = {
val bos = new ByteArrayOutputStream(input.length)
val gzip = new GZIPOutputStream(bos)
loadNumberOfItems("foo.bar") shouldBe a [Int]
// InvalidUrlException
loadNumberOfItems("http://google.com") shouldBe a [Int]
// InvalidPayloadException
loadNumberOfItems("http://actual.server.endpoint.com/number") shouldBe a [Int]
// ParsingException
loadNumberOfItems("http://actual.server.endpoint.com/number") shouldBe a [Int]
// ClassCastException
sealed trait Exception
case object InvalidUrl extends Exception
case object InvalidJson extends Exception
def loadNumberOfItems(url: String): Int = {
val json: Json = request(url)
json.getField("number").asInstanceOf[Int]
}
def loadNumberOfItems(url: String): IO[Either[Exception, Int]] =
Url(url)
.toRight(InvalidUrl)
.map(request(_))
.traverse(_.map(_.getFieldOption("number").flatMap(_.as[Int]).toRight(InvalidJson)))
.map(_.flatten)
def loadNumberOfItems(url: String): IO[Either[Exception, Int]] = {
val maybeUrl: Option[Url] =
Url(url)
val eitherUrl: Either[Exception, Url] =
maybeUrl.toRight(InvalidUrl)
val eitherJson: Either[Exception, IO[Json]] =
eitherUrl.map(u => request(u))
val eitherResult: Either[Exception, IO[Either[Exception, Int]]] =
eitherJson.map(futureJson =>
futureJson.map(json => json.getFieldOption("number").flatMap(x => x.as[Int]).toRight(InvalidJson)))
def count(p: A => Boolean): Int
def find(p: A => Boolean): Option[A]
def filter(p: A => Boolean): List[A]
def exists(p: A => Boolean): Boolean
def forall(p: A => Boolean): Boolean
Cafe.buyCoffee(creditCard) shouldBe (coffee, charge)
object Cafe {
def buyCoffee(creditCard: CreditCard): (Coffee, Charge) = {
val cup = new Coffee() // new coffee is created
(cup, Charge(creditCart, cup.price)) // cup and charge is returned
}
}
// Can be created without new keyword
case class Charge(creditCard: CreditCard, amount: Double)