Skip to content

Instantly share code, notes, and snippets.

@cuipengfei
Created December 15, 2013 13:20
Show Gist options
  • Select an option

  • Save cuipengfei/7973017 to your computer and use it in GitHub Desktop.

Select an option

Save cuipengfei/7973017 to your computer and use it in GitHub Desktop.
functional js recursion
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)
})
return result.sort()
}
module.exports = getDependencies
function getDependencies(tree) {
var result = []
function collect(subTree) {
if (subTree) {
for (prop in subTree) {
if (prop) {
if (result.filter(function (elem) {
return elem.name == prop && elem.version == subTree[prop].version
}).length == 0) {
result.push({name: prop, version: subTree[prop].version})
}
collect(subTree[prop].dependencies)
}
}
}
}
collect(tree.dependencies)
var arrayResult = result.map(function (elem) {
return elem.name + "@" + elem.version
}).sort(function (a, b) {
if (a > b) return 1
else return -1
})
//dont print, just return
// console.log(arrayResult)
return arrayResult
}
module.exports = getDependencies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment