Reputation: 23
Here are two working versions (for Node.js) of the same recursive function.
Version 1
function getDependencies(mod, result) {
result = result || []
var dependencies = mod.dependencies || []
Object.keys(dependencies).forEach(function(dep) {
var key = dep + '@' + mod.dependencies[dep].version
if (result.indexOf(key) === -1) result.push(key)
getDependencies(mod.dependencies[dep], result) // COMPARE THIS LINE
})
return result.sort()
}
Version 2
function getDependencies(mod, result) {
result = result || []
var dependencies = mod.dependencies || []
Object.keys(dependencies).forEach(function(dep) {
var key = dep + '@' + mod.dependencies[dep].version
if (result.indexOf(key) === -1) result.push(key)
result = getDependencies(mod.dependencies[dep], result) // COMPARE THIS LINE
})
return result.sort()
}
How does version 1 of the function work, as compared to version 2, without explicitly setting the result variable?
Upvotes: 0
Views: 74
Reputation: 781098
result.push(key)
and result.sort()
both modify the result
array that was passed in as an argument. So there's no need to assign it again in the caller.
Upvotes: 1