Tell us what’s happening:
I don’t know what else to do to pass tests 18 and 19.
The logic is correct, but the tests are not being validated.
Your code so far
<!-- file: index.html -->
/* file: styles.css */
let array = [];
const generateElement = () => {
const element = Math.floor(Math.random() * 100) + 1;
return element;
};
const generateArray = () => {
const array = [];
for (let i = 0; i < 5; i++) {
array.push(generateElement());
}
return array;
};
const generateContainer = () => {
const container = document.createElement('div');
return container;
};
const fillArrContainer = (elementHTML, arr) => {
elementHTML.innerHTML = '';
arr.forEach(num => {
const item = document.createElement('span');
item.textContent = num;
item.classList.add('array-item');
elementHTML.appendChild(item);
})
};
const isOrdered = (num1, num2) => {
return num1 <= num2;
};
const swapElements = (arr, index) => {
if(!isOrdered(arr[index], arr[index + 1])) {
[arr[index], arr[index + 1]] = [arr[index +1], arr[index]];
return true;
}
return false;
};
const highlightCurrentEls = (container, index) => {
const children = container.children;
const nextIndex = index + 1;
const style = '2px dashed red';
children[index].style.border = style;
children[nextIndex].style.border = style;
};
const generateBtn = document.getElementById("generate-btn");
const startingArr = document.getElementById("starting-array");
const sortBtn = document.getElementById("sort-btn");
const arrContainer = document.getElementById("array-container");
generateBtn.addEventListener("click", () => {
arrContainer.innerHTML = "";
startingArr.innerHTML = "";
arrContainer.appendChild(startingArr);
array = generateArray();
fillArrContainer(startingArr, array);
});
sortBtn.addEventListener("click", () => {
if (array.length === 0) return;
arrContainer.innerHTML = "";
arrContainer.appendChild(startingArr);
let tempArr = [...array];
let n = tempArr.length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n - 1; j++) {
if (i === 0 && j === 0) {
highlightCurrentEls(startingArr, j);
}
swapElements(tempArr, j);
const stepDiv = generateContainer();
fillArrContainer(stepDiv, [...tempArr]);
let nextJ = j + 1;
let nextI = i;
if (nextJ >= n - 1) {
nextJ = 0;
nextI++;
}
if (nextI < n) {
if (i === n - 1 && j === n - 2) {
arrContainer.appendChild(stepDiv);
} else {
highlightCurrentEls(stepDiv, nextJ);
arrContainer.appendChild(stepDiv);
}
}
}
}
const finalStep = generateContainer();
fillArrContainer(finalStep, [...tempArr]);
finalStep.style.border = '2px solid green';
arrContainer.appendChild(finalStep);
});
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:150.0) Gecko/20100101 Firefox/150.0
Challenge Information:
Build a Sorting Visualizer - Build a Sorting Visualizer