f3ry - 6 months ago 36

CoffeeScript Question

I need to create a tree that, for example CALCULATE 2 numbers. I do in coffee script, who connvert javascript due to extend class.

`class Expression`

@Evaluate = -> 0

class Const extends Expression

constructor: (value)->

class BinaryOperation extends Expression

constructor: (L, R)->

class Add extends BinaryOperation

@Evaluate = -> L.Evaluate() + R.Evaluate();

expr = new Add(new Const(10), new Const(10));

alert(expr.Evaluate())

Demo: https://jsfiddle.net/f3ry/D9kBP/24/

Thanks.

Answer

Your problem is a combination of syntax errors and a misunderstanding of how subclassing works. This should get you there:

```
class Expression
Evaluate: () -> 0
class Const extends Expression
constructor: (@value) ->
Evaluate: () -> @value
class BinaryOperation extends Expression
constructor: (@L, @R)->
class Add extends BinaryOperation
Evaluate: -> @L.Evaluate() + @R.Evaluate();
expr = new Add(new Const(10), new Const(10));
alert(expr.Evaluate())
```

Adding the `@`

to the constructor parameter sets it as a property of the newly created object. Overriding the `Evaluate`

method allows the operations to be performed. Link to example.