Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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/p5@vv1.4.0/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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!