简体   繁体   中英

How to rewrite loop to recursion

I implemented a search function and loop that search by collection. In first iteration I need to search by all collection, but all next iterations only by result of the first iteration. I use if-statement if (i >= 1) collection = result; to do it, but it's not safe because I need to save collection. Is it possible to rewrite loop to recursion function? How I can make it or make my code elegant?

var targets = target.split(' '); // => ['hello', 'world'];

for (var i = 0; i < targets.length; ++i) {
    if (i >= 1) {
        collection = result;
    }
    result = includes(collection, props, targets[i]);
}

My search function:

function includes(collection, props, target) {
    var result = [];
    var collection_length = collection.length;
    var props_length = props.length;
    var target_length = target.length;

    for (var i = 0; i < collection_length; ++i) {
        for (var j = 0; j < props_length; ++j) {
            if (collection[i][props[j]]) {
                if (collection[i][props[j]].toLowerCase().slice(0, target_length) === target) {
                    result.push(collection[i]);
                    continue;
                }
            }
        }
    }

    return result.length !== 0 ? result : false;
} 
var result = collection;
for (var i = 0; i < targets.length; ++i) {
    result = includes(result, props, targets[i]);
}

Maybe I'm missing something but isn't this what you're trying to do?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM