Skip to content

Function declaration invokes the function body #29

@RoboPhred

Description

@RoboPhred

Declaring a function causes the function to be invoked. This is particularly nasty for array iteration methods, where the iterator will get invoked an extra time with a null value.

Here is a test that pinpoints the issue:

test('function declaration does not invoke function', function(t) {
    t.plan(1);

    var invoked = false;
    var variables = {
        noop: function(){},
        onInvoke: function() {invoked = true}
    };
    var src = `noop(function(){ onInvoke(); })`;
    var ast = parse(src).body[0].expression;
    evaluate(ast, variables);
    t.equal(invoked, false);
})

Here is a failing test that demonstrates the array use case:

test('array methods invocation count', function(t) {
    t.plan(2);

    var variables = {
        values: [1, 2, 3],
        receiver: []
    };
    var src = 'values.forEach(function(x) { receiver.push(x); })'
    var ast = parse(src).body[0].expression;
    evaluate(ast, variables);
    t.equal(variables.receiver.length, 3);
    t.deepEqual(variables.receiver, [1, 2, 3]);
})

The result of the deepEqual check is:

    operator: deepEqual
    expected: [ 1, 2, 3 ]
    actual:   [ null, 1, 2, 3 ]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions