Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

158
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda