Skip to content

Instantly share code, notes, and snippets.

@olvnikon
Created October 6, 2017 11:24
Show Gist options
  • Select an option

  • Save olvnikon/66cf8d81ad635e623b77af4fb1d0eee5 to your computer and use it in GitHub Desktop.

Select an option

Save olvnikon/66cf8d81ad635e623b77af4fb1d0eee5 to your computer and use it in GitHub Desktop.

Revisions

  1. olvnikon created this gist Oct 6, 2017.
    40 changes: 40 additions & 0 deletions function-to-window.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    function isOnTheBody(path) {
    return path.scope.parent.isGlobal;
    }

    function transform(j, path) {
    const propName = path.value.id.name;
    const params = path.value.params;
    const body = path.value.body;

    j(path).replaceWith(
    j.expressionStatement(
    j.assignmentExpression(
    "=",
    j.memberExpression(
    j.identifier("window"),
    j.identifier(propName)
    ),
    j.functionExpression(
    j.identifier(propName),
    params,
    body
    )
    )
    )
    );
    }

    module.exports = function(fileInfo, api, options) {
    const j = api.jscodeshift;
    const ast = j(fileInfo.source);

    ast
    .find(j.FunctionDeclaration)
    .filter(isOnTheBody)
    .forEach((path, index) => {
    transform(j, path);
    });

    return ast.toSource();
    };