I am trying to make work a while loop in JS but I do not know much about js syntax.
Each time I test the following code I get an error ‘out of memory", so I think I need to fix the code but cant’ find what is not working
const template = [
{title: 'template 1', parentFolder:'', uniqueid: '1'},
{title: 'template 2-2', parentFolder:'', uniqueid: '22'},
{title: 'template 2-2', parentFolder:'', uniqueid: '222'},
{title: 'template 2-2-1', parentFolder:'', uniqueid: '333'},
];
template[0].parentFolder = template[0];
template[1].parentFolder = template[0];
template[2].parentFolder = template[0];
template[3].parentFolder = template[1];
// Function and get the folder to start from
function getFoldersPath(currentFolder) {
// Create an empty list to hold the full path
const previousParents = [];
// Add each parentFolder to the list until reaching the root parent
while (currentFolder.uniqueid !== template[0].uniqueid) {
previousParents.push(currentFolder.uniqueid);
currentFolder = currentFolder.parentFolder.uniqueid;
}
return previousParents;
}
var result = getFoldersPath(template[3])
console.log(result)
If someone could help me fix the code
>Solution :
The reason why the code is running out of memory is because of the while loop’s condition, which is not correctly checking the unique ID of the current folder against the unique ID of the root parent folder.
In the while loop, the condition ‘currentFolder.uniqueid’ !== template[0].uniqueid is always true because it’s comparing a string literal ‘currentFolder.uniqueid’ with the unique ID of the root parent folder. Instead of checking the value of the uniqueid property of the current folder, it’s checking against the string ‘currentFolder.uniqueid’ itself.
// Function and get the folder to start from
function getFoldersPath(currentFolder) {
// Create an empty list to hold the full path
const previousParents = [];
// Add each parentFolder to the list until reaching the root parent
while (currentFolder.uniqueid !== template[0].uniqueid) {
previousParents.push(currentFolder.uniqueid);
currentFolder = currentFolder.parentFolder;
}
return previousParents;
}
var result = getFoldersPath(template[3])
console.log(result)