Using reduce to sum array of p5.Vector objects

The following code throws an error in the line with reduce:

let vectors

function setup() {
    createCanvas(400,400);
    vectors = [];
    vectors.push(createVector(100,100));
    vectors.push(createVector(100,0));
    vectors.push(createVector(0,100));
    let s = vectors.reduce(p5.Vector.add, createVector(0,0));//error!
    console.log(s.x,s.y);
}

function draw() {
    vectors.forEach(v => line(0,0,v.x,v.y));
}

The error seems to occur in the p5.js code for the vector add method. The error message begins:

p5.js says: There's an error as "set" could not be called as a function (on line 91666 in p5.js [https://cdn.jsdelivr.net/npm/[email protected]/lib/p5.js:91666:22]).

What seems most baffling about this error is that the code works without error if the offending line is replaced by:

let s = vectors.reduce((u,v) => p5.Vector.add(u,v), createVector(0,0));

This is sufficient for my intended application, but I would like to understand the error rather than just find a kludgy way to sidestep it. My question is thus -- why does the attempt to use reduce directly with p5.Vector.add fail but wrapping it in an anonymous function succeed?


It looks like p5.Vector.Add can take in a third optional argument:

p5.Vector.add(v1, v2, [target])

In that example it defines target as such:

p5.Vector: the vector to receive the result (Optional)

In your original version you are passing arguments from the reduce function into p5.Vector.Add. However, the third argument for reduce is currentIndex, an integer.