Repeat string as multi-item list/array in PsychoJS

URL of experiment: https://pavlovia.org/nicbadcock/pab

Description of the problem: Repeating a string as a list in PsychoPy/Python is straight forward:

my_colour = "green"
number_repeats = 5
my_colour_list = [my_colour] * number_repeats
print(my_colour_list)

returns: [‘green’, ‘green’, ‘green’, ‘green’, ‘green’]
The PsychoPy to PsychoJS (I’ll use Py to JS to denote this) translation recommends:

my_colour = "green"
number_repeats = 5;
my_colour_list = ([my_colour] * number_repeats);

But this returns: NaN

Though not as elegant as a single line, it could be done with a loop. Py to JS suggests:

my_colour = "green";
number_repeats = 5;
my_colour_list = [];
for (var index = 0, _pj_a = number_repeats; (index < _pj_a); index += 1) {
    my_colour_list.append(my_colour);
}

But PsychoJS doesn’t recognise the append element. Though push seems to work (found here):

my_colour = "green";
number_repeats = 5;
my_colour_list = [];
for (var index = 0, _pj_a = number_repeats; (index < _pj_a); index += 1) {
    my_colour_list.push(my_colour);
}

So, I have a solution but I would prefer to learn how to do it in a single line if possible. I can see that there’s a java Class called Collections that has an option:

my_colour = "green";
number_repeats = 5;
my_colour_list = Collections.nCopies(number_repeats, my_colour);

but I don’t know how to import this into my PsychoJS script.

So I’ve ended up with two questions here:
1. Is there a single line of PsychoJS code that can repeat a string x times as a list/array?
2. How do you import external java classes into PsychoJS?

PS I’m not sure if there’s a way to flag (or tag) the need for Py to JS translation updates within a post - hopefully someone with the power spots it.

You can’t - Java and JavaScript are entirely different languages and are basically not related to each other. And yes, it is a mystery to me why anyone would ever intentionally choose to inflict this confusion upon the world.

Java is to JavaScript as Car is to Carpet
Java is to JavaScript as Ham is to Hamster
etc etc

Sorry, don’t know enough JavaScript to help with that.

Thanks @Michael - this is a very useful thing to know!

if I understand the question, then the solution is on my crib sheet:

Python
Using multiplication to create a larger array, e.g. [0, 1] * 10

JS
Array(10).fill([0,1]).flat();
Ref: dvbridges

1 Like

Perfect - this works a treat - thanks! I wonder if it’s possible to get your crib sheet on a website so Google can search it? Seems like a really helpful resource.

1 Like

While I could put it on a web page, it wouldn’t have the dynamic functionality of a Google doc. Anyone can suggest edits. Hopefully anyone using Google search would end up finding a link to it from this forum.

1 Like