Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the shorthand in d3 for the identity function ("function(d) { return d; }")?

Looking through the d3 docs, I see this code (the identity function) repeated everywhere:

function(d) { return d; }

Is there a built-in way in d3 to do this? I know I could create my own no-op identity function and use it everywhere, but it seems like d3 should provide this.

like image 290
Lukas Avatar asked Jun 22 '13 13:06

Lukas


People also ask

What does D3 select do?

select() function in D3. js is used to select the first element that matches the specified selector string. If any element is not matched then it returns the empty selection. If multiple elements are matched with the selector then only the first matching element will be selected.

What is D3 range?

d3. range returns an array of evenly-spaced numbers. In its simplest form, it returns the integers from zero to the specified end minus one. Array(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

What is domain and range in D3?

The domain is the complete set of values, so in this case that is all of your temperatures, from 33 to 64. The range is the set of resulting values of a function, in this case the resulting values of scaling your temperatures from 0 to 600.


2 Answers

I was wondering why there wasn't a d3.identity function as part of the library, and couldn't find a reason not to have one.

From a performance point of view, defining an identity function gives better performance than reusing the Object constructor. It makes little difference if you reuse the same identity function across different types. Some performance tests are here.

So in my case I abuse D3 and added the function myself:

d3.identity = function(d) { return d; }

If you're using underscore then you can also use the _.identity function.

Regarding using the Object constructor, my assumption is that this creates a new, unnecessary object each time it's called which wastes memory and CPU time, both for creation and garbage collection. This may be optimised away for immutable types such as numbers in some runtimes.

EDIT Phrogz has a brief article showing some useful shorthand for reducing the number of lambdas when working with D3, that includes an identity function.

like image 71
Drew Noakes Avatar answered Sep 19 '22 01:09

Drew Noakes


I used to see Mike do .data(Object) which seems to work

http://tributary.io/inlet/5842519

but I'm not sure why I don't see it around anymore

var svg = d3.select("svg")

var data = [[10,20],[30,40]];
svg.selectAll("g")
.data(data)
.enter()
.append("g")
.attr("transform", function(d,i) { return "translate(" + [i * 100, 0] + ")"})
.selectAll("circle")
//.data(function(d) { console.log(d); return d })
.data(Object)
.enter()
.append("circle")
.attr({
  cx: function(d,i) { return 100 + i * 40 },
  cy: 100,
  r: function(d,i) { return d }
})
like image 28
enjalot Avatar answered Sep 22 '22 01:09

enjalot