使用递归列出给定目录中的文件

时间:2019-01-26 20:23:20

标签: javascript algorithm recursion

我得到了一个这样的数据对象,其中[{...}]是同一类型的对象

pub struct GameMove {
    pub from: usize,
    pub to: usize,
    pub move_type: GameMoveType,
    pub piece_type: PieceType,
}
#[derive(PartialEq, Clone, Debug)]
pub enum GameMoveType {
    Quiet,
    Capture(PieceType),
}

#[derive(PartialEq, Clone, Debug)]
pub enum PieceType {
    King,
    Pawn
}

pub fn match_move_type(move_type: &GameMoveType) -> usize {
    match move_type {
        GameMoveType::Quiet => 0,
        GameMoveType::Capture(_) => 1,
    }
}

pub struct MoveFilter<'a> {
    legal_moves: Vec<GameMove>,
    move_type: GameMoveType,
}

impl IntoIterator for MoveFilter {
    type Item = &'a GameMove;
    type IntoIter = MoveFilterIterator;
    fn into_iter(self) -> Self::IntoIter {
        MoveFilterIterator {
            legal_moves: self.legal_moves,
            move_type: match_move_type(&self.move_type),
            index: 0,
        }
    }
}

pub struct MoveFilterIterator {
    legal_moves: Vec<GameMove>,
    move_type: usize,
    index: usize,
}

impl Iterator for MoveFilterIterator {
    type Item = &GameMove;
    fn next(&mut self) -> Option<&GameMove> {
        while self.index < self.legal_moves.len() {
            if match_move_type(&self.legal_moves[self.index].move_type) == self.move_type {
                Some(&self.legal_moves[self.index])
            } else {
                self.index += 1;
            }
        }
        None
    }
}

,我被要求返回dirName下的文件,包括它们的子目录。

我尝试使用for ... in循环遍历对象,但是通常这个问题有点困扰我,而递归地进行操作则更加困难。

{
 dirName: 'app',
 files: ['index.html', 'page.html'],
 subDirs: [{...}]
}

出于参考目的,您可以假设数据看起来像这样。

listFiles: function listFiles(data, dirName) {
    for (prop in data) {
      return data[prop];
    }
  },

返回参数

您应该能够从服务器检索数据并返回名称的排序数组

3 个答案:

答案 0 :(得分:-1)

尝试这一操作,它应该使用级联制表列出控制台中带有文件的所有目录:

function rec(dir, level = 0) {
    level++;
    console.log(`${' '.repeat((level-1)*5)}${dir.dirName}::`);
    console.log(dir.files.map(f => `${' '.repeat(level*5)}${f}`).join('\n'));
    dir.subDirs.forEach(d => rec(d, level));
}

那只是返回文件夹树中的所有文件:

function rec(dir) {
    return [...dir.files, ...dir.subDirs.flatMap(d => rec(d))];
}

这样称呼:

rec(fileData)

希望有帮助。

答案 1 :(得分:-1)

您可以返回目录和文件的组合,然后再次调用该函数以获取嵌套值。

function getFiles({ dirName, files = [], subDirs }) {
    return files
        .concat(...(subDirs ? subDirs.map(getFiles) : []))
        .map(f => [dirName].concat(f));
}

var data = { dirName: 'app', files: ['index.html'], subDirs: [{ dirName: 'js', files: ['main.js', 'app.js', 'misc.js'], subDirs: [{ dirName: 'vendor', files: ['jquery.js', 'underscore.js'], subDirs: [] }] }, { dirName: 'css', files: ['reset.css', 'main.css',], subDirs: [] }] },
    files = getFiles(data);

console.log(files.map(a => a.join('/')));
console.log(files);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:-1)

是学习mutual recursion的好时机。下面,list1调用listAll,后者调用list1 ...

const list1 = ({ dirName, files = [], subDirs = []}, pwd = '') =>
  [ ... files .map (f => `${pwd}/${f}`)
  , ... listAll (subDirs, `${pwd}/${dirName}`)
  ]

const listAll = (dirs = [], pwd = '') =>
  dirs .flatMap (d => list1 (d, pwd))

console .log (list1(fileData))
// [ "/index.html"
// , "/app/main.js"
// , "/app/app.js"
// , "/app/misc.js"
// , "/app/js/jquery.js"
// , "/app/js/underscore.js"
// , "/app/reset.css"
// , "/app/main.css"
// ]

展开以下代码段,以在您自己的浏览器中验证结果-

const fileData = {
    dirName: 'app',
    files: ['index.html'],
    subDirs: [
      {
        dirName: 'js',
        files: [
          'main.js',
          'app.js',
          'misc.js',
        ],
        subDirs: [
          {
            dirName: 'vendor',
            files: [
              'jquery.js',
              'underscore.js',
            ],
            subDirs: [],
          },
        ],
      },
      {
        dirName: 'css',
        files: [
          'reset.css',
          'main.css',
        ],
        subDirs: [],
      },
    ],
  };
  
const list1 = ({ dirName, files = [], subDirs = []}, pwd = '') =>
  [ ... files .map (f => `${pwd}/${f}`)
  , ... listAll (subDirs, `${pwd}/${dirName}`)
  ]

const listAll = (dirs = [], pwd = '') =>
  dirs .flatMap (d => list1 (d, pwd))
  
console .log (list1 (fileData))
// [ "/index.html"
// , "/app/main.js"
// , "/app/app.js"
// , "/app/misc.js"
// , "/app/js/jquery.js"
// , "/app/js/underscore.js"
// , "/app/reset.css"
// , "/app/main.css"
// ]