Description
Increasing Access
In my experience, iteration tends to be one of the most intimidating foundational programming concepts to beginners. As discussed in issue #6607, there are factors in every different structure for iteration that can be difficult for beginners.
The risk of crashing a browser tab with an infinite loop can be particularly discouraging. Iteration unlocks so many creative opportunities, and I think what p5 does best is lower barriers for creative opportunities.
This proposal offers a way to iterate without the risk of infinite loops. It does so with syntax that I would argue is one of the simplest and easiest to read. As such, I am proposing this to increase accessibility of iteration.
Most appropriate sub-area of p5.js?
- Accessibility
- Color
- Core/Environment/Rendering
- Data
- DOM
- Events
- Image
- IO
- Math
- Typography
- Utilities
- WebGL
- Build Process
- Unit Testing
- Internalization
- Friendly Errors
- Other (specify if possible)
Feature request details
I propose adding a range() function that returns an iterator for a sequence of numbers for be used in for...of loops. I built this function as an add-on called p5.range. I can submit this as a library, but I think this may be a helpful addition to p5's base library.
One factor that came up in issue #6607 is that introducing a new structure for iterating over arrays vs numerical iteration faces beginners with new, unfamiliar syntax. Using range() would allow for one consistent format for both:
Numerical
// 100 random circles
for(let count of range(100)) {
circle(random(width), random(height), random(100));
}
// A row of circles starting 25 units from the left,
// spanning the width of the canvas,
// 50 units apart
for(let x of range(25, width, 50)) {
circle(x, height / 2, 50);
}
Array
for(let index of range(myArray.length)) {
myArray[index] += 1;
}
3 statement for loop for comparison:
Numerical
// 100 random circles
for(let count = 0; count < 100; count += 1) {
circle(random(width), random(height), random(100));
}
// A row of circles starting 25 units from the left,
// spanning the width of the canvas,
// 50 units apart
for(let x = 0; x < width; x += 50) {
circle(x, height / 2, 50);
}
Array
for(let index = 0; index < myArray.length; index += 1) {
myArray[index] += 1;
}
This proposed function is inspired by Python's range function.
From Processing Python reference:
loadPixels()
for i in range((width*height/2)-width/2):
pixels[i] = pink
updatePixels()
Notably, the proposed function uses for...of rather than for...in, which do different things in JS. This has been noted as a concern for causing confusion with beginners in #6607. I would argue, though, that the risk of accidentally passing in array keys instead of values is less discouraging that crashing the browser tab. If for...in were used with this range() function, it would simply do nothing, but the program would still run otherwise.
Metadata
Metadata
Assignees
Type
Projects
Status