I'm doing a code challenge with the following solution:
let files = {a: {b: true}}
// return 'a/b'
function getPath(file) {
let output = [];
for (key in file) {
if (file[key] instanceof Object) {
let saved = key
console.log(`Before getPath ${key}`)
let paths = getPath(file[key])
console.log(`After getPath ${key}`)
paths.forEach((path) => {
output.push(`${saved}/${path}`)
})
} else {
output.push(`${key}`)
}
}
return output
}
getPath(files)
Why would the "key" changes before and after let paths = getPath(file[key])
? In this recursion, there would be two levels of for-in loop. Is it possible that the inner for-in loop is causing the issue due to scope/context problem? Is it because "key" ignores function scope and mutates it?