minimising code in if condition using javascript

Viewed 67

I wrote a code

if(!fs.existSync(path.join(data,file,path)){
 fs.mkdirSync(path.join(data,file,path));
}


if(!fs.existSync(path.join(another,file)){
 fs.mkdirSync(path.join(another,file));
}


if(!fs.existSync(path.join(new,file,temp,path)){
 fs.mkdirSync(path.join(new,file,temp,path));
}

so i have to write path.join(data,file,path), path.join(new,file), path.join(another,file,temp,path) 2 times is there any way i can minimize this line? or should i leave this like this only ?

or i put this in one Array and then mkdir

array= 
[path.join(data,file,path),
 path.join(new,file), 
 path.join(another,file,temp,path)
]
if(fs.existSync(array.include){
fs.mkdirSync(array.include)
}

is this possible ?

3 Answers

You could use a function like this so you don't repeat code

function mkdir(data,file,p){
    var dir = path.join(data,file,p);
    if(!fs.existSync(dir)
        fs.mkdirSync(dir);
}

mkdir(data,file,path);
mkdir(another,file,path);
mkdir(yetanother,file,path);

Using an array you could do this

var arr = [path.join(data,file,p), path.join(another,file,p)];

function mkdir(p){
    if(!fs.existSync(p)
        fs.mkdirSync(p);
}

arr.forEach(mkdir);

I can't see any scope of improvement unless you want to write a new method to check the fs.existSync() {which is not a good idea}

You can use this code :

var array =[another , new, data];

array.forEach(element =>{
  if(!fs.existSync(path.join(element,file,path))
      fs.mkdirSync(path.join(element,file,path));

});
Related