重构嵌套数组比较迭代器(循环)

时间:2017-04-21 08:09:21

标签: javascript node.js loops web iterator

任何人都可以指出我是否正确迭代两个数组。有没有其他方法可以在不嵌套迭代器的情况下编写代码?

下面的代码迭代两个对象数组,使用下划线库比较值。我最初使用嵌套for循环编写这些。

我再也没有要求直接回答,我自学成才,我有时觉得做的事与他们应该如何完成相反。

function getFilesAdded( directoryData ) {
    return new Promise(function( resolve, reject ) {
        _.each(liveDirectories, function( liveDirectory ) {
            _.each(directoryData, function( directory ) {
                if ( directory.DirectoryName === liveDirectory.DirectoryName && directory.Files.length > liveDirectory.NumOfFiles ) {
                    var filesAdded = [];
                    numOfFilesAdded = directory.Files.length - liveDirectory.NumOfFiles;
                    fileArray = orderByTimeAdded(directory.Files, directory.DirectoryName);
                    fileArray.slice(0, numOfFilesAdded).forEach(pushToArray(filesAdded))
                    liveDirectory.NumOfFiles = directory.Files.length;
                    filesAddedCount === 0 ? (filesAddedCount++, reject()) : (resolve(_.sortBy(filesAdded, 'FileName')));
                }
            })
        })
    })
}

liveDirectories

[ 
    { 
       DirectoryName: './zaf/betting', 
       NumOfFiles: 5 
    },
    { 
       DirectoryName: './zaf/racecard', 
       NumOfFiles: 5 
    } 
]

directoryData

[ 
    { 
        DirectoryName: './zaf/betting',
        Files:
         [ 'b1.txt',
           'b2.txt',
           'b3.txt',
           'b4.txt',
           'betting_files_here.txt' ] 
    },
    { 
        DirectoryName: './zaf/racecard',
        Files:
         [ 'r1.txt',
           'r2.txt',
           'r3.txt',
           'r4.txt',
           'racecard_files_here.txt' ] 
    } 

1 个答案:

答案 0 :(得分:0)

基于给出建议的代码

感谢大家的帮助。

function iterateAddedFiles( numOfFilesAdded, fileArray, filesAdded ) {
    fileArray.slice(0, numOfFilesAdded).forEach(pushToArray(filesAdded))
}

function getFilesAdded( directoryData ) {
    return new Promise(function( resolve, reject ) {
        var dirMap = new Map()
        _.each(liveDirectories, function( liveDirectory ) {
            dirMap.set(liveDirectory.DirectoryName, liveDirectory)
        })
        _.each(directoryData, function( directory ) {
            var liveDir = dirMap.get(directory.DirectoryName)
            if ( directory.Files.length > liveDir.NumOfFiles && count > 0) {
                var fileArray = [];
                filesAdded = [];
                numOfFilesAdded = directory.Files.length - liveDir.NumOfFiles
                fileArray = orderByTimeAdded(directory.Files, directory.DirectoryName);
                iterateFiles(numOfFilesAdded, fileArray, filesAdded)
                liveDir.NumOfFiles = directory.Files.length;
                count++
                resolve(_.sortBy(filesAdded, 'FileName'))
            } else {
                count++
            }
        })
    })
}