0

I would like to call, from ScalaJS, a JS function similar to the following:

function parseExpression(s){
  if(isNumber(s)) return {lit:s}
  else{
    return {
      left : leftOp(s)
      oper : operand(s)
      right: rightOp(s)
    }
  }
}

where the returned object can be of two different shapes, either {lit} or {left, oper, right}

I have defined the following traits in ScalaJS:

@js.native
trait NumLiteral extends js.Object{
  val lit:String = js.native
}

@js.native
trait NumOper extends js.Object{
  val left : NumLiteral | NumOper = js.native
  val oper : String = js.native
  val right: NumLiteral | NumOper = js.native
}

then I can declare function parseExpression as Function1[String, NumLiteral | NumOper]

What is the best way of checking if the returned value of parseExpression(someExpressionString) is of type NumLiteral or NumOper? I am free to change the JS and/or the Scala code to achieve the most elegant solution.

Eduardo
  • 8,362
  • 6
  • 38
  • 72

1 Answers1

0

I solved it by defining the following in ScalaJS:

trait NumExpr

@JSExport
class NumLiteral(val lit:String) extends NumExpr

@JSExport
class NumOper(val left:NumExpr, val oper:String, val right:NumExpr) extends NumExpr

and then redefining my JS function to:

function parseExpression(s){
  return isNumber(s) ?
    new NumLiteral(s) :
    new NumOper(leftOp(s), operand(s), rightOp(s))
}

This lets me pattern-match on parseExpression(someExpressionString)

Of course, this changes the original JS function, and therefore the original question, but it solved my problem.

Eduardo
  • 8,362
  • 6
  • 38
  • 72