Last active
August 29, 2015 14:00
-
-
Save tstone/11164429 to your computer and use it in GitHub Desktop.
Javascript in Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Function "add" implemented in javascript | |
function add(x, y) { | |
return x + y; | |
} | |
// Function "add" implemented in Scala as javascript is actually implementing it behind the scenes | |
sealed abstract class DynamicType | |
case class Int(value: BitSet) extends DynamicType | |
object Int { | |
def add(x: Int, y: Int) = ??? | |
def toString(x: Int) = ??? | |
} | |
case class String(value: BitSet) extends DynamicType | |
object String { | |
def add(x: String, y: String) = ??? | |
} | |
case class Function extends DynamicType { | |
var apply: () => this.type | |
var prototype = Map[String, DynamicType]() | |
} | |
case class Object extends Function | |
case class Array(value: ???) extends DynamicType { | |
def toString = Array.join(value, ",") | |
} | |
object Array { | |
def join(ar: Array) = ??? | |
} | |
// --- add --- | |
def add(x: DynamicType, y: DynamicType) x match { | |
case x: Int => y match { | |
case y: Int => Int.add(x, y) | |
case y: String => String.add(x.toString(), y) // 5 + "6" >> "56" | |
case y: Object => String.add(x.toString(), y.toString()) // 6 + {} >> "6[object Object]" | |
case _ => throw new Exception | |
} | |
case x: String => y match { | |
case y: String => String.add(x, y) | |
case y => String.add(x, y.toString()) // "a" + function f(){} >> "afunction f(){}" | |
} | |
case _: Function => y match { | |
case y: Int => y.toString() // function f(){} + 6 >> "6" | |
case y: Array if y.length == 0 => 0 // function f(){} + [0] >> 0 | |
case y: Array if y.length == 1 => y[0] // function f(){} + [6] >> 6 | |
case _ => throw new NotANumberException // function f(){} + {} >> NaN | |
} | |
case a: Array => String.add(a.toString , y.toString) // [5,6] + [4,5] >> "5,64,5" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment