-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCode.js
80 lines (67 loc) · 2 KB
/
Code.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var pkgInstaller = function (inputObj) {
/*Running pre-checks to check input validity*/
if (inputObj === null || !Array.isArray(inputObj))
throw 'Invalid input';
inputObj.forEach(function(value) {
if (typeof value !== 'string')
throw 'Input data type invalid';
});
/*Creating a shallow copy of the input*/
var copyinputObj = inputObj.slice();
/*Iterating through the input and scanning the package and its dependency*/
var parsePackages = function() {
var output = {};
copyinputObj.forEach(function(item) {
var items = item.split(':');
var key = items[0].trim();
var value = items[1].trim();
if (key.length === 0) {
throw 'Invalid package';
}
if (!output[key]) output[key] = [];
if (!output[value] && value.length > 0) output[value] = [];
if (value.length > 0)
output[key].push(value);
});
return output;
}
/* Used to arrange / sort the input after checking its respective dependency*/
var sortPkgDep = function(parsedPackages) {
var output = [];
var sorted = {};
Object.keys(parsedPackages).forEach(function(key) {
sort(key, []);
});
function sort(key, parentReq) {
if (sorted[key])
return;
parentReq.push(key);
var pkg = parsedPackages[key];
pkg.forEach(function(dependency) {
if (parentReq.indexOf(dependency) >= 0) {
throw 'Invalid dependency link';
}
sort(dependency, parentReq);
});
sorted[key] = true;
output.push(key);
}
return output;
}
return {
checkInsDep: function() {
var parsedPackages = parsePackages();
return sortPkgDep(parsedPackages).join(', ');
}
};
};
/* Sample Input*/
var checkInput = [
"KittenService: ",
"Leetmeme: Cyberportal",
"Cyberportal: Ice",
"CamelCaser: KittenService",
"Fraudstream: Leetmeme",
"Ice: "];
/*Running output onto console*/
console.log(pkgInstaller(checkInput).checkInsDep());