Skip to content

Instantly share code, notes, and snippets.

@ben196888
Last active September 7, 2023 09:47
Show Gist options
  • Save ben196888/12714d184e483c4d1a15f42535529fb5 to your computer and use it in GitHub Desktop.
Save ben196888/12714d184e483c4d1a15f42535529fb5 to your computer and use it in GitHub Desktop.
Typescript to Scala cheatsheet

Scala cheatsheet for typescript developers

Variable

// typescript
const str: string = ""
let count: number = 0
// scala
val str: String = ""
// It is not recommended to use var in scala
var count: Int = 0

Loop

// typescript
const list: number[] = [3, 1, 2, 5]
const result: number[] = []
for (let element of list) {
  result.push(element * 2)
}

const verX: number[] = [1, 0, 3, 5]
const verY: number[] = [0, 8, 2, 4]

const result: number[] = []
for (let x of verX) {
  for (let y of verY) {
    result.push(x * y)
  }
}
// scala
val list: Seq[Int] = Seq(3, 1, 2, 5)

val result = for {
  element <- list
} yield {
  element * 2
}

val verX: Seq[Int] = Seq(1, 0, 3, 5)
val verY: Seq[Int] = Seq(0, 8, 2, 4)

val result = for {
  x <- verX
  y <- verY
} yield {
  x * y
}

Function

// typescript
function add(x: number, y: number): number {
  return x + y
}

function innerProduct(verX: number[], verY: number[]): number {
  return verX.map((x, idx) => x * verY[idx]).reduce(add, 0)
}
// scala
def add(x: Int, y: Int): Int = x + y

def innerProduct(verX: Seq[Int], verY: Seq[Int]): Int = {
  val products = for {
    (x, y) <- verX.zip(verY)
  } yield {
    x * y
  }
  products.reduceLeft(add)
}

Map, Reduce

// typescript
const animals: Animal[] = ['๐Ÿฎ', '๐Ÿท', '๐Ÿ”']

const meats: Meat[] = animals.map(getMeat) // ['๐Ÿฅฉ', '๐Ÿ–', '๐Ÿ—']

const animalToMeatMap: Record<Animal, [Animal, Meat]> = animals
  .reduce((m, animal) => ({
      ...m,
      [animal]: getMeat(animal),
    }),
  {})
// { '๐Ÿฎ': '๐Ÿฅฉ', '๐Ÿท': '๐Ÿ–', '๐Ÿ”': '๐Ÿ—' }
// scala
val animals: Seq[Animal] = Seq("๐Ÿฎ", "๐Ÿท", "๐Ÿ”")
val meats: Seq[Meat] = animals.map(getMeat) // Seq("๐Ÿฅฉ", "๐Ÿ–", "๐Ÿ—")
val animalToMeatMap: Map[Animal, Meat] = {
  val animalToMeatPairs = for {
    animal <- animals
    meat = getMeat(animal)
  } yield (animal, meat)
  animalToMeatPairs.toMap
}
// Map("๐Ÿฎ" -> "๐Ÿฅฉ", "๐Ÿท" -> "๐Ÿ–", "๐Ÿ”" -> "๐Ÿ—")

Json

// typescript
interface Request {
  userId: number,
  postId: number,
}

const request: Request = { userId: 123, postId: 456 }
const requestString: string = JSON.stringify(request)

interface Response {
  success: boolean,
  data: { userId: number, postId: number },
  error: string,
}

const responseString: string = '{ "success": true, "data": { "userId": 123, "postId": 456 }, "error": ""  }'
const response: Response = JSON.parse(responseString)

// type casting
const requestJson: any = request
const requestString: string = JSON.stringify(requestJson)

const responseJson: any = JSON.parse(responseString)
const response: Response = responseJson as Response
// scala
// prefer to use circe JSON parser, https://www.baeldung.com/scala/circe-json for more details
import io.circe._, io.circe.parser._, io.circe.generic.semiauto._
final case class Request(userId: Int, postId: Int)

object Request {
  implicit val jsonDecoder: Decoder[Request] = deriveDecoder[Request]
  implicit val jsonEncoder: Encoder[Request] = deriveEncoder[Request]
}

final case class Data(userId: Int, postId: Int)
final case class Response(success: Boolean, data: Data, error: String)

object Response {
  implicit val jsonDecoder: Decoder[Response] = deriveDecoder[Response]
  implicit val jsonEncoder: Encoder[Response] = deriveEncoder[Response]
}

val requestString: String = Request(123, 456).asJson.noSpaces

val responseString: String = """{ "success": true, "data": { "userId": 123, "postId": 456 }, "error": ""  }"""
val response: Response = decode[Response](responseString).getOrElse(Response(false, Data(0, 0), ""))

// type casting
val requestJson: Json = Request(123, 456).asJson
val requestString: String = requestJson.noSpaces

val responseJson: Json = parse(responseString).getOrElse(Json.Null)
val response: Response = responseJson.as[Response].getOrElse(Response(false, Data(0, 0), ""))

Inspired by Scala for Javascript Developers & Scala.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment