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)]; } }