Wednesday, September 7, 2016

D3 - Coding with Readability and Usefulness, no more d variable

One of the things I find so irritating is the overuse of letters which lack sufficient readability (to understand code without having to dig into the back-end to gain meaning).

I'm learning and working on D3 stuff and I see many examples using the letter d. This d stands for data, obviously. BUT, almost everything in the world is a d (i.e. data). Needless to say, I had to update code to ensure better understanding and programming. Here's my example of better coding using D3.

Before

groups.selectAll('text')
    .data(function (d) {
        console.log(d);
        return d;
    })
    .enter()
    .append('text')
    .text( function (d, i) {
        console.log(i);
        if (typeof d === 'number')
        {
            console.log("data type is a number, not object...skipping.");
            return;
        }
        console.log(d);
        return d.x;
    });

After

groups.selectAll('text')
    .data(function (arr) {
        console.log(arr);
        return arr;
    })
    .enter()
    .append('text')
    .text( function (obj, i) {
        console.log(i);
        if (typeof obj === 'number')
        {
            console.log("data type is a number, not object...skipping.");
            return;
        }
        console.log(obj);
        return obj.x;
    });

In the After, I updated the d within the data method into "arr" as its a data array representing the dataset passed in. I updated the d within the text method into "obj" as its a data object of the data array passed in.

I hope this helps somebody.

Blessings,

No comments:

Post a Comment