Last active
July 26, 2021 14:08
-
-
Save ArjArav98/bf67cea316155321c19727ac15cafe3e to your computer and use it in GitHub Desktop.
Searching Directories For Files (Recursive vs Iterative)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Both of these implementations are pseudocodes. | |
// The objective of both of these implementations is to check | |
// if a file exists inside a directory or not. It does not have to be | |
// directly present inside the directory. | |
// In the ITERATIVE version, we have to define 2 functions and it's a lot less readable. | |
// The RECURSIVE version is much more readable and induces a lesser cognitive load | |
// (ease of understanding) on the person reading it. | |
// Decide for yourself which implementation is better in this case! | |
/*====================*/ | |
/* RECURSIVE FUNCTION */ | |
/*====================*/ | |
function recursiveFileSearch (currentDirectory, fileToFind) { | |
let childDirectories = getChildDirectories() | |
let files = getFilesDirectory(currentDirectory) | |
for (let i=0; i<files.length; i+=1) { | |
if (files[i] == fileToFind) return true; | |
} | |
for (let i=0; i<childDirectories.length; i+=1) { | |
if (recursiveFileSearch(childDirectories[i], fileToFind)) return true; | |
} | |
return false; | |
} | |
/*====================*/ | |
/* ITERATIVE FUNCTION */ | |
/*====================*/ | |
function getAllSubdirectories (currentDirectory) { | |
// This function will get all subdirectories, not just | |
// immediate children directories. | |
// Using a Breadth-First Search (BFS) implementation, | |
// and using a stack, we get this list. | |
// Not typing out the entire algorithm for brevity's sake. | |
return subdirectories; | |
} | |
function iterativeFileSearch (currentDirectory, fileToFind) { | |
let subdirectories = getAllSubdirectories(currentDirectory); | |
for (let i=0; i<subdirectories.length; i+=1) { | |
let files = getFilesDirectory(subdirectories[i]); | |
for (let j=0; j<files.length; j+=1) { | |
if (files[j] == fileToFind) return true; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment