javascript - How to extract common methods into a function -
i want extract common method chains prevent copy paste identical code.
how in javascript way ?
original
if(this.get('with_coverage')){ svg.append("text") .attr("x", (width / 2)) .attr("y", 0 - (margin.top / 2)) .attr("text-anchor", "middle") .style("font-size", "16px") .style("text-decoration", "underline") .text("with coverage"); } else{ svg.append("text") .attr("x", (width / 2)) .attr("y", 0 - (margin.top / 2)) .attr("text-anchor", "middle") .style("font-size", "16px") .style("text-decoration", "underline") .text("without coverage"); }
expected
var apply_style = attr("x", (width / 2)) .attr("y", 0 - (margin.top / 2)) .attr("text-anchor", "middle") .style("font-size", "16px") .style("text-decoration", "underline"); if(this.get('with_coverage')){ svg.append("text") .apply_style() .text("with coverage"); } else{ svg.append("text") .apply_style() .text("without coverage"); }
svg.append("text") .attr("x", (width / 2)) .attr("y", 0 - (margin.top / 2)) .attr("text-anchor", "middle") .style("font-size", "16px") .style("text-decoration", "underline") .text("with"+(this.get('with_coverage')?"":"out")+" coverage");
some people don't ternary operators mixed in code. in case can this:
function applystylebasedoncondition(selection, actions, condition, t, f){ actions.call(selection); (condition ? t : f).call(selection); } applystylebasedoncondition(svg.append("text"), function(){ .attr({ x: width / 2, y: 0 - (margin.top / 2), "text-anchor": "middle" }) .style({ "font-size": "16px", "text-decoration": "underline" }); }, this.get('with_coverage'), function(){ this.text("with coverage"); }, function(){ this.text("without coverage"); });
Comments
Post a Comment