Maak een nieuwe array op basis van een groeisorteeralgoritme, begint bij de oorsprong en groeit vervolgens geleidelijk naar het begin en begin van de array.
Example use case: Loading images for a scroll animation sequence and start loading at a specific percentage
const imagesArray = [
"image1.jpg",
"image2.jpg",
"image3.jpg",
"image4.jpg",
"image5.jpg",
"image6.jpg",
"image7.jpg",
"image8.jpg",
"image9.jpg",
"image10.jpg",
"image11.jpg",
"image12.jpg",
"image13.jpg",
"image14.jpg",
"image15.jpg",
"image16.jpg",
"image17.jpg",
"image18.jpg",
"image19.jpg",
"image20.jpg"
];
function growSortIndexes(arr = [], origin = 0) {
const startIndex = Math.min(origin, Math.max(0, arr.length - 1));
const indexes = [startIndex];
for (let offset = 1; offset < arr.length - 1; offset++) {
if (arr[startIndex + offset]) {
indexes.push(startIndex + offset);
}
if (arr[startIndex - offset]) {
indexes.push(startIndex - offset);
}
}
return indexes;
}
growSortIndexes(imagesArray, 10); // [10, 11, 9, 12, 8, 13, 7, 14, 6, 15, 5, 16, 4, 17, 3, 18, 2, 19, 1, 0]
function growSort(arr = [], origin = 0) {
const startIndex = Math.min(origin, Math.max(0, arr.length - 1));
const indexes = [arr[startIndex]];
for (let offset = 1; offset < arr.length - 1; offset++) {
if (arr[startIndex + offset]) {
indexes.push(arr[startIndex + offset]);
}
if (arr[startIndex - offset]) {
indexes.push(arr[startIndex - offset]);
}
}
return indexes;
}
growSort(imagesArray, 10); // ['image11.jpg', 'image12.jpg', 'image10.jpg', 'image13.jpg', 'image9.jpg', 'image14.jpg', 'image8.jpg', 'image15.jpg', 'image7.jpg', 'image16.jpg', 'image6.jpg', 'image17.jpg', 'image5.jpg', 'image18.jpg', 'image4.jpg', 'image19.jpg', 'image3.jpg', 'image20.jpg', 'image2.jpg', 'image1.jpg']