Luke
Luke

Reputation: 557

Why is my recursive function returning undefined?

I am working through day 7 of the Advent of Code and am stuck on why my code is returning undefined when the base case in findNestedBags hits the first condition (data[key].includes(color)). It returns 0 when the second case is true so I am confused why one works and the other doesn't.

The objective is to figure out how many different bags will lead to a bag that contains a 'shiny gold' bag. If a certain colored bag contains a shiny gold bag as an option (found in the value of key/value pair), it's an option. Alternatively, if one of the bags in list then has shiny gold as an option in its key/value pair, that can count as well...

This is a sample of the data structure as found in the variable data, just with many more rows:


data = {
  'vibrant violet': [ 'light gray', 'wavy aqua' ],
  'dim fuchsia': [ 'vibrant white', 'pale beige', 'shiny gold' ],
  'drab fuchsia': [ 'dotted turquoise', 'dull crimson', 'plaid violet' ],
  'dim purple': [ 'plaid silver', 'posh gray', 'plaid beige' ],
  'mirrored lavender': [ 'vibrant lime', 'vibrant violet', 'mirrored aqua', 'clear black' ],
  'posh green': []
}
let data = indexData(input);

let count = 0;
function findMatches(color, input) {
    for (let key in input) {
        
        if (input[key].includes(color)) {
            count++
        }
        else {
            let x = findNestedBags(key, color, input)
            if (x == 1) count++
        }
    }
    return count
}

function findNestedBags(key, color, data) {
    if (data[key].includes(color)) {
        return 1
    }

    else if (data[key].length == 0) {
        return 0;
    }
    else {
        data[key].forEach(item => {
            return findNestedBags(item, color, data)
        })
    }

}

Upvotes: 2

Views: 178

Answers (1)

Unmitigated
Unmitigated

Reputation: 89214

forEach does not return a value. If you want to sum all the results, you can use Array#reduce. In addition, you can set the accumulator's initial value to 0 by passing in a second argument, so you can remove the check for the array's length being 0.

function findNestedBags(key, color, data) {
    if (data[key].includes(color)) {
        return 1
    } else {
        return data[key].reduce((acc,item) => {
            return acc + findNestedBags(item, color, data)
        }, 0)
    }
}

Upvotes: 2

Related Questions