Split URL into segments
Defect per line of code.

Code defects AKA bugs have a strong correlation to the number of lines of code (*1). Across all languages, coding styles, and domains there is a consistent defect rate. The industry average is about 20 per 1000 lines of code.

The metric is simple. 


  "... a count of lines in the text of the program's source code excluding comment lines." (*2)


One of the simplest ways to reduce defects is to reduce the number of lines. This dose not mean putting everything in one line is a good idea, nor does it mean that sprawling out what would be a single line, to many lines, does not add to the line count.

Reducing your code

So with that in mind your code is a little low density, meaning that there are more lines than are needed to do what you want done.

Reducing your code while still using the same logic yields the following



const path = 'rootFolder/folder1/exampleFolder1/folder3/folder3/subFolder123/file2.md';

const info = path.split('/').map((name, index, dirs) =&gt; {
    const item = {name};
    if (index &lt; dirs.length - 1) {
        item.url = '';
        for (let i = 0; i &lt;= index; i++) {
            item.url += `/${dirs[i]}`;
        }
    }
    return item;
});

console.log(info);




Ignoring the top and bottom lines we now have 10 lines.

This is still a little long as the inner loop is just a Array.join but limited to the current index. 

If we look for ways to reduce the size we can see that the need to exclude the URL from the file name is adding complexity. Unless there is a good reason to not have the URL we can just treat all items equally.



const path = 'rootFolder/folder1/exampleFolder1/folder3/folder3/subFolder123/file2.md';

const dirs = path.split('/');
const info = [];
while (dirs.length) { 
    info.unshift({ url : "/" + dirs.join("/"), name : dirs.pop() });
}

console.log(info);




We are now down to 5 lines. And personally info can share the declaration with dirs



const path = 'rootFolder/folder1/exampleFolder1/folder3/folder3/subFolder123/file2.md';

const info = [], dirs = path.split('/');
while (dirs.length) { 
    info.unshift({ url : "/" + dirs.join("/"), name : dirs.pop() });
}

console.log(info);




We have reduced the number of lines from 12 to 4, reducing the chance of defect by over half.




- (*1) Steve McConnell, Code Complete



- (*2) wiki, Source lines of code