Skip to content

Instantly share code, notes, and snippets.

@keyserfaty
Last active September 18, 2016 13:50
Show Gist options
  • Save keyserfaty/3e1cf52997a343cbb66b07e90bd77c2c to your computer and use it in GitHub Desktop.
Save keyserfaty/3e1cf52997a343cbb66b07e90bd77c2c to your computer and use it in GitHub Desktop.
Some Scala functions turned Javascript

Factorial

Scala

def factorial(n: Int) = {
  def tailFactorial(n: Int, acc: Int): Int =
    if (n == 0) acc else tailFactorial(n - 1, acc * n)

  tailFactorial(n, 1)
}

Javascript

const factorial = n => {
  const tailFactorial = (n, acc) => {
     if (n === 0) return acc
     else return tailFactorial(n - 1, acc * n)
  }
  
  return tailFactorial(n, 1)
}

Square root of a number

Scala

def abs(x: Double) = if (x < 0) -x else x

def sqrt(x: Double) = {
  def sqrtIter(guess: Double): Double =
    if (isGoodEnough(guess)) guess
    else sqrtIter(improve(guess))


  def isGoodEnough(guess: Double) =
    abs(guess * guess - x) < 0.000001

  def improve(guess: Double) =
    (guess + x / guess) / 2

  sqrtIter(1.0)
}

Javascript

const abs = x => x < 0 ? -x : x

const sqrt = x => {
  const sqrtIter = guess => {
    if (isGoodEnough(guess)) return guess
    else return sqrtIter(improve(guess))
  }
  
  const isGoodEnough = guess =>
    abs(guess * guess - x) < 0.00001
  
  const improve = guess =>
    (guess + x / guess) / 2
  
  return sqrtIter(1.0)
}

Pascal's triangle

def main(args: Array[String]) {
  for (row <- 0 to 10) {
    for (col <- 0 to row)
      print(pascal(col, row) + " ")
    println()
  }
}

def pascal(c: Int, r: Int): Int = {
  if (c == 0 | c == r) 1
  else pascal(c - 1, r - 1) + pascal(c, r - 1)
}
@okbel
Copy link

okbel commented Sep 14, 2016

💯

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