Javier Cárdenas
Javier Cárdenas

Reputation: 4045

source code in tickSize d3.js v4

I'm trying to understand the tickSize documentation in d3.js v4:

axis.tickSize([size]) <>

If size is specified, sets the inner and outer tick size to the specified value and returns the axis. If size is not specified, returns the current inner tick size, which defaults to 6.

When I check the source code I get this:

axis.tickSize = function(_) {
    return arguments.length ? (tickSizeInner = tickSizeOuter = +_, axis) : tickSizeInner;
  };

I don't really understand what is going on.

Source: https://github.com/d3/d3-axis/blob/master/src/axis.js#L140

Upvotes: 2

Views: 619

Answers (1)

Andrew Reid
Andrew Reid

Reputation: 38231

The method will return the current value for tickSizeInner if there are no arguments provided for the method. Alternatively it will set the tickSizeInner and tickSizeOuter variables if an argument is provided.

This is done in this line:

return arguments.length ? (tickSizeInner = tickSizeOuter = +_, axis) : tickSizeInner;

Which is a use of the ternary operator which is a shorthand method for this:

if(arguments.length)  {
    tickSizeInner = tickSizeOuter = +_; return axis 
}
else {
   return tickSizeInner; 
}

See also this question, King's answer or this doc regarding commas with ternary operations.

Here's a stripped down version of the function logic:

function tick(_) {
    return arguments.length ? _ : 6;
  };
  
console.log(tick())
console.log(tick(4))

The beauty in this sort of approach is your getter and setter method is one and the same.

Note that zero in javascript is falsey, take a look at the lines below (undefined is also falsey, included for comparison, see also this):

if(0) { console.log("true"); }
else { console.log("false"); }

if(1) { console.log("true"); }
else { console.log("false"); }

if(undefined){ console.log("true"); }
else { console.log("false"); }

So, if no argument is passed, then the current tick size is returned. If an argument is passed (underscore is a valid variable name, see this question), then it is forced into a number (+_) and set to equal the tick sizes (See this question's top answer for converting strings to numbers).

Here's an example of forcing variables to integers:

var a = "1";
var b = "2";

console.log(a+b);

a = +a;
b = +b;

console.log(a+b);

And lastly, you can assign values to multiple variables in the manner shown in the code. For example:

var a = 0;
var b = 0;

a = b = 5;

console.log(a);
console.log(b);

Upvotes: 2

Related Questions