Yh1234
Yh1234

Reputation: 151

Using for loop to order dependency

var input = [  "KittenService: ",   "Leetmeme: Cyberportal",   "Cyberportal: Ice",   "CamelCaser: KittenService",   "Fraudstream: Leetmeme",   "Ice: "];

var output = [];

function valid(input) {
  for(var i = 0; i < input.length; i++) {
    var array = input[i].trim().split(':');
    var packageName = array[0].trim();
    var dependencyName = array[1].trim();
    if(array.length > 1 && dependencyName === '') {

      if(output.indexOf(packageName) === -1) {
        output.push(packageName);
      }
      else {
        return;
      }
    }
    else if(array.length > 1 && dependencyName !== '') {
      if (output.indexOf(dependencyName) === -1) { 
      output.push(dependencyName); 
      if(output.indexOf(dependencyName) > -1) {
        if(output.indexOf(packageName) > -1) {
         continue;
         }
         else {
           output.push(packageName);
         }
       }
      }
      else if(output.indexOf(dependencyName) > -1) {
        output.push(packageName);
      }
    }
  }
  return output.join(', ');
 }
 valid(input);

I am trying to figure out way to make the output to become

"KittenService, Ice, Cyberportal, Leetmeme, CamelCaser, Fraudstream"

Right it logs

'KittenService, Cyberportal, Leetmeme, Ice, CamelCaser, Fraudstream'

I am not sure how to make all the input with dependencies to pushed before input with dependencies.

Upvotes: 0

Views: 58

Answers (1)

johnc
johnc

Reputation: 106

Problem was just that you were returning if no package name instead of using a continue.

var input =[ "KittenService: CamelCaser", "CamelCaser: " ]

var output = [];

function valid(input) {
  for(var i = 0; i < input.length; i++) {
    var array = input[i].trim().split(':');
    var packageName = array[0].trim();
    var dependencyName = array[1].trim();
    if(array.length > 1 && dependencyName === '') {

      if(output.indexOf(packageName) === -1) {
        output.push(packageName);
      }
      else {
        continue;
      }
    }
    else if(array.length > 1 && dependencyName !== '') {
      if (output.indexOf(dependencyName) === -1) { 
        output.push(dependencyName); 
        if(output.indexOf(dependencyName) > -1) {
          output.push(packageName);
        }
      }
    }
  }
  return output;
}
console.log(valid(input));

Upvotes: 2

Related Questions