Home > Net >  Walking up a file's path backwords
Walking up a file's path backwords

Time:06-08

Starting with a string that has the full path of a file I threw together this function to walk up the directories of the file's path backwards. It works, but my gut tells me I'm overcooking the plumbing and I decided that this was a good opportunity for a learning experience. How would I refactor this to be more succinct?

const path = require('path')

function walk(file) {
    let dir = path.dirname(file)
    let arr = dir.split('/').filter(e => e).reverse()
    let paths = []
    for(let i = arr.length; i >= 0; i--) {
        let sub = arr.slice(i)
        paths.push(sub.reverse().join('/'))
    }
    paths = paths.filter(e => e).reverse()
    paths.forEach(path => {
        console.log('/'   path)
    })
}

walk('/D0/D1/D2/D3/foo.bar')

CodePudding user response:

Another simpler recursive version:

const path = require('path');

function walk(start) {
  const dir = path.dirname(start)
  console.log(dir);
  if (dir !== '/') {
    walk(dir);
  }
}

walk('/D0/D1/D2/D3/foo.bar');

It will output:

"/D0/D1/D2/D3"
"/D0/D1/D2"
"/D0/D1"
"/D0"
"/"

CodePudding user response:

You could use a recursive function.

I let you here an example

const path = require('path')

function walk(file) {
    let dir = path.dirname(file)
    walkRecursively(dir.split('/'))
}

function walkRecursively(dirs) {
  if(dirs.length < 2) {
    return;
  }
  console.log(path.join(dirs))
  const nextDirs = dirs.slice(0, -1)
  walkRecursively(nextDirs)
}

walk('/D0/D1/D2/D3/foo.bar')

CodePudding user response:

you can do something like this

function walk(file) {
    const path = file.split('/').filter(e => e).slice(0, -1)
    const result = path.reduce((res, p, i) => {
      return [
        ...res,
        `${res[i - 1] || ''}/${p}`
      ]
    }, []).reverse()
    console.log(result)
}

walk('/D0/D1/D2/D3/foo.bar')

  • Related