D3 Helpers

0.3.0 · abandoned · verified Sun Apr 19

d3-helpers is a collection of small, functional utility functions designed to streamline common D3 callback patterns, particularly for D3.js version 3.0. It aims to improve code readability by allowing a left-to-right composition style for data property access and function application within D3's data-driven methods, such as `d3.svg.line().x()`. The package, currently at version 0.3.0, was last published in 2014 and is not actively maintained. It was developed to abstract away repetitive callback definitions like `function (d) { return x(new Date(d.date)); }` into more concise and explicit chains like `d3h('date', d3h.newDate, x)`. Its primary differentiator was simplifying D3's functional programming aspects at a time when D3's API encouraged verbose callback structures. It offers utilities for property access, type conversion, and handling data `d` and index `i` arguments in a declarative manner.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates using `d3h` to compose property access and function application for D3 line generator callbacks, mimicking its original usage with D3v3.

const d3h = require('d3-helpers');

// Mock D3 and scale functions for demonstration
const d3 = {
  svg: {
    line: () => ({
      _x: null,
      _y: null,
      x: function(fn) { this._x = fn; return this; },
      y: function(fn) { this._y = fn; return this; },
      // Simulate line generation
      generate: function(data) {
        return data.map(d => ({ x: this._x(d), y: this._y(d) }));
      }
    })
  }
};

const xScale = d => d * 10;
const yScale = d => d * 5;

// Sample data
const data = [
  { date: '2024-01-01', y: 10 },
  { date: '2024-01-02', y: 20 },
  { date: '2024-01-03', y: 15 }
];

// Original D3 code style (simulated)
// const lineBefore = d3.svg.line()
//   .x(function (d) { return xScale(new Date(d.date).getTime()); })
//   .y(function (d) { return yScale(+d.y); });
// console.log('Before:', lineBefore.generate(data));

// D3 code with d3-helpers
const line = d3.svg.line()
  .x(d3h('date', d3h.newDate, d => d.getTime(), xScale))
  .y(d3h('y', Number, yScale));

const generatedPoints = line.generate(data);
console.log('Generated line points with d3-helpers:');
console.log(generatedPoints);
// Expected output: 
// [
//   { x: <timestamp for 2024-01-01> * 10, y: 50 },
//   { x: <timestamp for 2024-01-02> * 10, y: 100 },
//   { x: <timestamp for 2024-01-03> * 10, y: 75 }
// ]

view raw JSON →