timoxley / functional-javascript-workshop

A functional javascript workshop. No libraries required (i.e. no underscore), just ES5.
2.06k stars 441 forks source link

exercise 16, recursion #124

Open BenjaminVerble opened 8 years ago

BenjaminVerble commented 8 years ago

worked on this with a friend. our understanding was that we could not use for loops (which we thought would exclude forEach as well)

it's a little ugly. does anyone have a recursion-only version that is easier to understand?

function getDependencies (tree) {

  var solution = {}

  if (tree.dependencies) {
    addDeps(tree.dependencies)
  }

  var answer = Object.keys(solution)

  return answer.sort()

  function addDeps (deps) {
    var keys = Object.keys(deps)
    processDeps(keys, deps)
  }

  function processDeps (keys, deps) {
    if (keys.length) {
      var currentKey = keys.pop()
      var currentObject = deps[currentKey]
      var nameVersionString = makeNameAtVersion(currentKey,currentObject.version)
      solution[nameVersionString] = 1
      if (currentObject.dependencies) {
        addDeps(currentObject.dependencies)
      }

      processDeps(keys, deps)

    }
  }

}

function makeNameAtVersion (name, version) {
  return `${name}@${version}`
}
GodStorm91 commented 8 years ago
function getDependencies(tree){
  var arr = [];
  var tempArr = [];
  var hasit = false
  var tempResult = '';
  var k;
  if ( tree == undefined ){
    return
  }
  if ( tree.hasOwnProperty('dependencies')){
    hasit = true
    var obj = tree['dependencies'];
    for ( j in tree['dependencies'] ){

      tempResult = j + '@' + obj[j].version
      tempArr =  getDependencies(obj[j])
      if ( tempArr.length > 0 ){
          arr = tempArr.concat(arr);
      }
      arr.push(tempResult);
    }
  }else{
  }
  return arr
}

module.exports = getDependencies
abdalla commented 7 years ago

Hi Benjamin, I didn't do that yet, but if I understood your question you can use reduce, take a look on my repo concatAll (https://github.com/abdalla/concatAll/blob/master/index.js) I'm using recursion stuff.

Hope it helps you.

BenjaminVerble commented 7 years ago

@abdalla : thanks!