Skip to content

Instantly share code, notes, and snippets.

@gilbert
Last active September 29, 2017 04:50
Show Gist options
  • Select an option

  • Save gilbert/b8d7a8e8506c7443da479ffaff3730d1 to your computer and use it in GitHub Desktop.

Select an option

Save gilbert/b8d7a8e8506c7443da479ffaff3730d1 to your computer and use it in GitHub Desktop.

Revisions

  1. gilbert revised this gist Sep 29, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion index.js
    Original file line number Diff line number Diff line change
    @@ -38,7 +38,7 @@ function getTempId(scope) {

    //
    // Converts:
    // (10 |> obj.f) |> g;
    // 10 |> obj.f |> g;
    // To:
    // (_x = 10, _x = obj.f(_x), _x = g(_x));
    //
  2. gilbert created this gist Sep 29, 2017.
    5 changes: 5 additions & 0 deletions actual.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,5 @@
    var inc = (x) => x + 1;
    var double = (x) => x * 2;

    var x = 10 |> inc |> double;
    var y = 10 |> inc;
    8 changes: 8 additions & 0 deletions expected.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    var _tmp;

    var inc = x => x + 1;

    var double = x => x * 2;

    var x = (_tmp = 10, _tmp = inc(_tmp), double(_tmp));
    var y = (_tmp = 10, inc(_tmp));
    57 changes: 57 additions & 0 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    import syntaxPipelines from "babel-plugin-syntax-pipelines";

    export default function({ types: t }) {
    return {
    inherits: syntaxPipelines,

    visitor: {
    BinaryExpression(path) {
    if (path.node.operator === "|>") {
    //
    // Transform the pipeline!
    //
    const tempVar = getTempId(path.scope);
    const assignments = pipe(t, tempVar, path.node.left).concat([
    t.callExpression(
    path.node.right,
    [tempVar]
    )
    ]);

    path.replaceWith( t.sequenceExpression(assignments) );
    }
    },
    },
    };
    }

    //
    // Limits the variable generation to one per scope
    //
    function getTempId(scope) {
    let id = scope.path.getData("pipelineOp");
    if (id) return id;

    id = scope.generateDeclaredUidIdentifier("tmp");
    return scope.path.setData("pipelineOp", id);
    }

    //
    // Converts:
    // (10 |> obj.f) |> g;
    // To:
    // (_x = 10, _x = obj.f(_x), _x = g(_x));
    //
    function pipe(t, tempVar, node) {

    if (node.operator === "|>" && node.type === "BinaryExpression") {
    const decl = t.assignmentExpression(
    '=',
    tempVar,
    t.callExpression( node.right, [tempVar]),
    );
    return pipe(t, tempVar, node.left).concat([decl]);
    } else {
    return [t.assignmentExpression('=', tempVar, node)];
    }
    }