Created
December 15, 2013 13:20
-
-
Save cuipengfei/7973017 to your computer and use it in GitHub Desktop.
functional js recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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