When applying scales to data elements in D3, it's common to combine the scale with an accessor function in order to apply the scale to the appropriate key on a data object. In this lesson, we'll create scaled accessors to refactor and tighten up some existing code.
Andy Van Slaars: [0:00] When working with data objects in D3, it's common to have to use an accessor to grab the value off of the data based on its key, and then apply that value to a scale. We see this nesting here with our Y scale wrapped around our Y accessor.
[0:13] Then again, down here for the width, where we use the X accessor, and then wrap the returned value in a call to the X scale. Let's refactor this and create scaled accessors, so that we can clean this code up a little bit and keep our component a little easier to read.
[0:27] I'm going to come up here and right below my definition for bandwidth, I'm just going to define a new constant called scaledX. ScaledX is going to take in a data point and then we'll call scale. The value for X scale is going to be our X accessor applied to our data element.
[0:47] I can duplicate this, and we'll use that as a template to create scaledY, where we apply our Y scale to the result of the Y accessor applied to our data. Now that we have these utilities defined, let's go down into our component code and clean this up just a little bit. We're going to call scaledY on our datum to get our transform. We'll call scaledX on our datum to get the width of our bars.
[1:17] I'll save that and everything should still render exactly the same, but now our component code is a little cleaner, a little easier to read.