Passing parameters into ES6 closure (for multiple P5.js sketches)

I am trying to make a ‘generic’ P5.js sketch that I can tweak based on a passed-in parameter, with the intent being to be able to generate multiple sketches on a single page to show how different inputs work side-by-side.

Following the guide I see syntax like this (and I’ve extended it to fill in multiple divs:

const s = ( sketch ) => {

  let x = 100;
  let y = 100;

  sketch.setup = () => {
    sketch.createCanvas(500, 500);
    console.log(idx);
  };

  sketch.draw = () => {
    sketch.background(100);
    sketch.fill(255);
    sketch.rect(x,y,50,50);
    sketch.text
  };
};

let myp5_1 = new p5(s, document.getElementById('p5-sketch1'));
let myp5_2 = new p5(s, document.getElementById('p5-sketch2'));
let myp5_3 = new p5(s, document.getElementById('p5-sketch3'));

I am not great with ES6, but I’m struggling with passing a set of parameters in to be able to tweak the P5.js code.

What I would like to do is to pass in, say, an ID variable into each instance of s and have the sketch execute differently, rather than making three separate const s calls and duplicating data.

Answer

Create a function that takes idx and returns the original function.

const s = (idx) => ( sketch ) => {

  let x = 100;
  let y = 100;

  sketch.setup = () => {
    sketch.createCanvas(500, 500);
    console.log(idx);
  };

  sketch.draw = () => {
    sketch.background(100);
    sketch.fill(255);
    sketch.rect(x,y,50,50);
    sketch.text
  };
};

let myp5_1 = new p5(s(0), document.getElementById('p5-sketch1'));
let myp5_2 = new p5(s(1), document.getElementById('p5-sketch2'));
let myp5_3 = new p5(s(2), document.getElementById('p5-sketch3'))