【问题标题】:How do you transform this code into pure functional javascript?您如何将此代码转换为纯函数式 javascript?
【发布时间】:2021-08-01 08:29:39
【问题描述】:
var files = [];
for (const entry of Object.entries(collection)) {
    var folder = "";
    entry.forEach(item => {
        if (typeof item == "string") {
            folder = item;
        }

        if (typeof item == "object") {
            item.forEach(file => {
                files.push(folder + "/" + file); // append files only (recursive)      
            })
        }
        
    });
    // sometimes lists contain names of children directories. check with the top parent to exclude directory names
    files = files.filter(x => !Object.keys(collection).includes(x));
}
console.log(files);

有一个javascript对象collection,它是代表某个目录的键值对的集合。
每个键都是子目录的名称,其值是列表类型,特别是仅在该目录内的文件名列表。

此代码有效,它通过一些额外的逻辑和连接递归地从基本目录中获取绝对文件路径名称的列表。

我很难重写这段代码来纯粹使用 .map()、.filter()、.find()、.pipe() 或 curry 方法

感谢反馈

【问题讨论】:

  • 这个问题可能更适合Code Review。但是,请务必在发布之前使用他们的tour 并阅读他们的How to Ask 页面。

标签: javascript dictionary filter functional-programming


【解决方案1】:

我的回答

var files = Object.entries(collection)
            .map(entries => entries
            .filter(entry => typeof entry == "object")
            .map(files => files
            .map(file => entries[0] + "/" + file))) // first entry will be the folder name to concatenate
            .flat().flat()
            .filter(x => !Object.keys(collection).includes(x));

返回列表和计数正确

【讨论】:

    【解决方案2】:

    我认为这可以帮助您入门, 我还建议编辑 Q 并为此功能添加 inputoutput 的示例...

    const join = ([folder, files]) => files.reduce(
      (res, file) => ({...res, [`${folder}/${file}`]: 1 }),
      {},
    );
    
    const fn = ([head, ...tail]) => Object
      .assign(join(head), tail.length ? fn(tail) : {});
      
    const toUniquePaths = (data) => Object.keys(
      fn(Object.entries(data)),
    );
    
    // ====
    
    const data = {
      a: ['a1', 'a2', 'a3', 'a4', 'a5'],
      b: ['b1', 'b2', 'b3', 'b4', 'b5'],
      c: ['c1', 'c2', 'c3', 'c4', 'c5'],
      d: ['d1', 'd2', 'd3', 'd4', 'd5'],
      e: ['e1', 'e2', 'e3', 'e4', 'e5', /* dupes */ 'e5', 'e4'],
    };
    
    console.log(
      toUniquePaths(data),
    );

    【讨论】:

      猜你喜欢
      • 2020-05-07
      • 2020-09-29
      • 1970-01-01
      • 2020-06-07
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      相关资源
      最近更新 更多