Skip to content

repeat()

Make Your Own Algorithmic Art edited this page Aug 15, 2018 · 10 revisions

Why?

Javascript's for loop structure is difficult for many new learners. It's not just children age 6-10 that find it difficult, even first year undergraduate students have found it difficult.

Logo, a visual language invented in 1967, has a particularly intuitive and simple loop structure:

REPEAT 4 [ FORWARD 100 RIGHT 90 ]

If all that's needed is t repeat something 4 times, the usual for loop is far too complex.

It isn't possible to implement this easily in Javascript sadly do we'll have to compromise and create a function which takes a function to be repeated. That's not ideal, but at least avoid the complexity of loop counters, continuation conditions and counter increments/decrements.


Details

There are two basic forms of the repeat() command.

repeat(n, my_function)

Repeats n times, a supplied function my_function . You will have to provide the my_function yourself.

repeat(start, end, step, my_function)

Repeats the supplied function my_function passing it a parameter that starts at start, ends at end, increasing in steps of step. The parameter's values will include start and end. The supplied my_function must accept a single parameter, this loop counter, which it can choose to use or ignore.


Nested Loops

There is a third form of the repeat() command to support nested loops.

repeat(outerloop_start, outerloop_end, outerloop_step, innerloop_start, innerloop_end, innerloop_step, my_function)

This form runs an outer loop which has a counter starting at outerloop_start, increasing by outerloop_step, until it reaches outerloop_end. For each of these loops, an inner loop is also run, with an inner loop counter starting at innerloop_start, increasing by innerloop_step, until it reaches innerloop_end. The supplied function my_function is passed both counters as parameters. The parameter values will include the start and end values. The supplied my_function must accept two parameters, these loop counters, which it can choose to use or ignore.


Example and Test

A test sketch demonstrates repeating a function my_circle 5 times.

It also demonstrates the use of the second form of repeat with a function my_square(x) where x starts from 100, grows by 50, until it reaches 400.

There is also a demonstration of a nested loop, with a grid of circles being drawn by a function my_blob(x, y) where x and y range over all combinations from 100 to 200 in steps of 20.

https://github.com/makeyourownalgorithmicart/simple.js/blob/master/examples/sketch_repeat.js

This image produced by the example code illustrates the three forms of repeat.

Clone this wiki locally