Code coverage report for lib/def.js

Statements: 100% (22 / 22)      Branches: 100% (10 / 10)      Functions: 100% (3 / 3)      Lines: 100% (22 / 22)      Ignored: none     

All files » lib/ » def.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62    1       1 121 121   121   3530 3530       6 6 6                                   3524       75         121 3   121     1 121 121 121 121 121     1  
'use strict';
 
var parse = require('esprima').parse,
    replace = require('estraverse').replace,
    generate = require('escodegen').generate
 
function fix (fn, cxt) {
    var changes = 0;
    var ast = parse('fn = ' + fn.toString());
 
    replace(ast, {
        leave: function (node) {
            var index;
            if (
                node.type === 'CallExpression' &&
                node.callee.type === 'Literal'
            ) {
                index = cxt.O[node.callee.value].index;
                changes++;
                return {
                    type: 'CallExpression',
                    callee: {
                        type: 'MemberExpression',
                        computed: true,
                        object: {
                            type: 'ThisExpression'
                        },
                        property: {
                            type: 'Literal',
                            value: index,
                            raw: (index + '')
                        }
                    },
                    arguments: []
                };
            }
 
            if (
                node.type === 'ExpressionStatement' &&
                node.expression.type === 'UpdateExpression'
            ) {
                this.remove();
            }
 
        }
    });
    if (changes) {
        eval(generate(ast));
    }
    return fn;
}
 
function def (name, fn, cxt) {
    var index = cxt.L.length;
    name = name.toLowerCase();
    cxt.L.push({name: name});
    cxt.O[name] = {index: index};
    cxt[index] = fix(fn, cxt);;
}
 
module.exports = def;