stream,做减法,优化搜索代码。

做一个搜索,三个输入条件,求这个条件的交集。起初我的思路是按照操作的流程,一步步的来做这三个筛选。

let searchResults = [];
//step1 根据id搜索,得到一个子集。
if (searchId) {
    //开始按照id查找,查找目标为allData
    let eds = allData;
    searchResults = this._searchWithId(searchId, eds);
    searchFlag = true;
}

if (searchTime) {
    //开始按照searchtime查找,如果searchFlag为true则查找目标为searchResults,否则为allData
    searchTime = Number(searchTime);
    if (searchFlag === true) {
        let srs = [];
        srs= this._searchWithMilliSeconds(searchId, searchResults );
        searchResults = srs;
    } else {
        let eds = allData;
        searchResults = this._searchWithMilliSeconds(searchId, eds);
    }

    searchFlag = true;
}

if (searchWords) {
    //开始按照searchwords查找,如果searchFlag为true则查找目标为searchResults,否则为allData
    if (searchFlag === true) {
        let srs = [];
        srs = this._searchWithKeyWord(searchId, searchResults );

        searchResults = srs;
    } else {
        let eds = allData;
        searchResults = this._searchWithKeyWord(searchId, eds);
    }

    searchFlag = true;
}
let result = searchDataStream;

经过某同事的帮助,采用做减法的思想,数据就像是流一样被filter掉。代码就被缩减了好多。主要是思路和经验,大家看看,细节请忽略

let searchDataStream = allData;
if (searchId) {
    //开始按照id查找,查找目标为_editLineDatas
    searchDataStream = this._searchWithId(searchId, searchDataStream);
}

if (searchTime) {
    //开始按照searchtime查找,如果searchFlag为true则查找目标为searchResults,否则为_editLineDatas
    searchTime = Number(searchTime);
    searchDataStream = this._searchWithMilliSeconds(searchTime, searchDataStream);
}

if (searchWords) {
    //开始按照searchwords查找,如果searchFlag为true则查找目标为searchResults,否则为_editLineDatas
    searchDataStream = this._searchWithKeyWord(searchWords, searchDataStream);
}
let result = searchDataStream;

你可能感兴趣的:(stream,做减法,优化搜索代码。)