Search code examples
javascriptd3.jschainingchain

Creating a d3 style chained function


I get how to do chained functions like a = x().y().z(), but I was looking to make something like d3 shape functions with 2 sets of parens at the end. ex: d = d3.line().curve('somecurve')([[10, 60], [40, 90]]).

The best I got is:

function gc() {
    gen = function (z) {
      console.log(x + y + z)
    }
    gen.setx = function(d) {x = d; return(this)}
    gen.sety = function(d) {y = d; return(this)}

    return gen
}

a = gc().setx(1).sety(2)
b = gc().setx(3).sety(4)

a(5)
b(6)

Which results in:

12

13

Which is clearly wrong as the second call is somehow overwriting the x,y state of the first call.

Any pointers would be appreciated!


Solution

  • In your code, x, y, and gen are global variables. So if two of these functions are both writing to them, they'll be overwritten. You'll need to create a separate set of variables each time gc is called. For example:

    function gc() {
        let x = 0; // <----- added
        let y = 0; // <----- added
        const gen = function (z) {
          console.log(x + y + z)
        }
        gen.setx = function(d) {x = d; return(this)}
        gen.sety = function(d) {y = d; return(this)}
    
        return gen
    }
    
    a = gc().setx(1).sety(2)
    b = gc().setx(3).sety(4)
    
    a(5)
    b(6)