Bob Napkin
Bob Napkin

Reputation: 566

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;
} 

Upvotes: 0

Views: 148

Answers (1)

melpomene
melpomene

Reputation: 85767

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?

Upvotes: 1

Related Questions