Javascript functions with Chapbook (Story javascript seems not to work)

Hello,
I tried using a javascript function to randomly rearrange an array of objects. If I put the function in a passage, no problem. If I put it in the javascript story, it doesn’t work. Am I forgetting something?
Cedric

s1:{nom:'Souris1',description:"descriptionLongue_s1",descriptionCourte:'descriptionCourte_s1'}
s2:{nom:'Souris2',description:"descriptionLongue_s2",descriptionCourte:'descriptionCourte_s2'}
s3:{nom:'Souris3',description:"descriptionLongue_s3",descriptionCourte:'descriptionCourte_s3'}

souris:[s1,s2,s3]
--
[JavaScript]
const shuffleArray = array => {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
};
shuffleArray(souris);
write ('<ul>');
for (enfant of souris) {
write('<li>' + enfant.nom + ' : ' + enfant.description + '</li>');
};
write('</ul>');

[cont]

Without testing the code I would guess that it’s a matter of Scope.

The contents of the Story JavaScript area is likely being executed in one Private Scope, and the contents of the current Passage in another Private Scope. So the shuffleArray() function you’re defining in Story JavaScript isn’t visible/available in the Passage.

There are a number of ways you can make your function more “global like” in nature, one of the simplest is to define your own Namespace on the web-browser’s window object and then define your function on that namespace.
(untested Story JavaScript code example)

if (!window.GE) {
	window.GE = {};
}

GE.shuffleArray = array => {
	for (let i = array.length - 1; i > 0; i--) {
		const j = Math.floor(Math.random() * (i + 1));
		const temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}
};

(untested Passage code example)

s1:{nom:'Souris1',description:"descriptionLongue_s1",descriptionCourte:'descriptionCourte_s1'}
s2:{nom:'Souris2',description:"descriptionLongue_s2",descriptionCourte:'descriptionCourte_s2'}
s3:{nom:'Souris3',description:"descriptionLongue_s3",descriptionCourte:'descriptionCourte_s3'}

souris:[s1,s2,s3]
[JavaScript]
GE.shuffleArray(souris);
write ('<ul>');
for (enfant of souris) {
write('<li>' + enfant.nom + ' : ' + enfant.description + '</li>');
};
write('</ul>');

note: Obviously you should replace GE in the above examples with your own unique Namespace name.

1 Like

Beautiful, it works perfectly. You are incredibly responsive and it is always a very good solution. Thank you very much and very good end of Sunday