export default function move(list: List, source: string, destination: string): List { const fileIDs: Array = []; const folderIDs: Array = []; // file for (let i = 0; i < list.length; i++) { list[i].files.forEach((file) => fileIDs.push(file.id)); } // folder list.forEach((folder) => folderIDs.push(folder.id)); function checkValueInArray(arr: Array, key: string) { return arr.find((a) => a === key); } const checkSourceIsFile = checkValueInArray(fileIDs, source); const checkSourceIsFolder = checkValueInArray(folderIDs, source); if (checkSourceIsFile === undefined) { if (checkSourceIsFolder !== undefined) { throw new Error('You cannot move a folder'); } else { throw new Error('This ID does not even exist, dude'); } } const checkDestinationIsFolder = checkValueInArray(folderIDs, destination); const checkDestinationIsFile = checkValueInArray(fileIDs, destination); if (checkDestinationIsFolder === undefined) { if (checkDestinationIsFile !== undefined) { throw new Error('You cannot specify a file as the destination'); } else { throw new Error('This ID does not even exist, dude'); } } function getFolderIdOfSource(list: List, source: string): number { for (let i = 0; i < list.length; i++) { if (list[i].files.find((item) => item.id === source)) { return i; } } return -1; } const sourceFolderID = getFolderIdOfSource(list, source); const folderObject = list[sourceFolderID]; let mutateObject = list[sourceFolderID]; mutateObject = { ...folderObject, files: folderObject.files.filter((i) => i.id !== source), }; list[sourceFolderID] = mutateObject; function folderIdOfDestionation(list: List, destination: string): number { for (let i = 0; i < list.length; i++) { if (list[i].id == destination) { return i; } } return -1; } const destinationFolderID = folderIdOfDestionation(list, destination); const fileToMove = folderObject.files.find((item) => item.id === source)!; list[destinationFolderID].files.push(fileToMove); return list; }