Matrix
Matrix

Reputation: 3369

Why || = not compiled such that if we use [] or not, in coffeescript?

why this difference:

class Foo
  getTest: ->
    @test ||= 42

compiled to:

return this.test || (this.test = 42);

different of

class Foo
  getTest: ->
    @test['bar'] ||= 42

is compiled in :

var _base;
return (_base = this.test)['bar'] || (_base['bar'] = 42);

what is the usefulness of this variable "_base"?!

return this.test['bar'] || (this.test['bar'] = 42);

is a good way too, no?

thx.

Upvotes: 1

Views: 24

Answers (1)

mu is too short
mu is too short

Reputation: 434785

There are two broad categories of structures that ||= needs to consider:

simple_expr  ||= x
complex_expr ||= x

A simple expression would be something like @test: (probably) no side effects and (probably) no performance penalty to evaluating it twice.

A complex expression would be anything else: @test['x'], @test(11).pancakes, ... Complex expression could have side effects or could be expensive so you only want to evaluate them once.

Now consider how many times expr1 is evaluated in:

expr1 || (expr1 = expr2)

Sometimes expr1 will be evaluated twice so CoffeeScript is stashing as much of expr1 as it can in _base to avoid the expense and possible side effects of evaluating expr1 twice.

You might also notice that for simple expressions, that only possible thing to stash in _base is the whole expression itself. I suspect that they're actually defaulting to considering all expressions complex and then leaving out _base when it turns out that there's nothing to stash in it.

Upvotes: 2

Related Questions