Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - function argument

I am learning Javascript, and bit confused the below usage. These question may be more javaScript than d3 specific.

http://mbostock.github.com/d3/ex/sunburst.html

var arc = d3.svg.arc()
.startAngle(function(d) { return d.x; })
.endAngle(function(d) { return d.x + d.dx; })
.innerRadius(function(d) { return Math.sqrt(d.y); })
.outerRadius(function(d) { return Math.sqrt(d.y + d.dy); });

so,

  1. startAngle, endAngle etc takes a function as argument. What is the rationale being the argument a function rather than just a number?
  2. In the full code, no where "d" is defined.I see it in almost all of d3 programs. What is "d" for? How is it set or where is it passed?

thanks.

like image 415
bsr Avatar asked Feb 21 '23 06:02

bsr


2 Answers

To your first question:

The d3.svg.arc object is used to create slices inside a pie diagram. Each of these slices needs a different start- and end-angle to be displayed properly.

In d3.js you do not pass in both angles for each slice, but provide a function, that takes one argument d, which is the corresponding data element for that slice and returns the angles. The same holds for the other parameters set here.

Another advantage is, that a datum can consist of multiple properties and you can decide which property takes which part with respect to the visualization.

Your second question

When using a function as a parameter to another function, it is common to use a function expression of the given form. In d3.js most functions, that serve as parameters, get passed in one or two parameters themselves (most of the time the part of the data, that needs to be transformed). In your function expression you need (or at least should) name those parameters in order to address them. Most of the time in the example d is used as the parametername for the parameter holding the specific data item.

It doesn't need to be defined elsewhere as it is just a normal function parameter. If you wish, you could rewrite it in the following way:

function startAngleParam( d ) {
 return d.x;
}

var arc = d3.svg.arc()
.startAngle( startAngleParam )
...
like image 80
Sirko Avatar answered Feb 27 '23 12:02

Sirko


d is very clearly passed as the argument to the anonymous function. Presumably these functions can take numbers as arguments, or a function for more complex operations (kind of like how String.replace() can take a replacement string, OR a function through which to run the result array and that returns the replacement value)

like image 37
Niet the Dark Absol Avatar answered Feb 27 '23 11:02

Niet the Dark Absol