forked from urfu-2015/javascript-tasks-4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiterator.js
More file actions
97 lines (90 loc) · 3.15 KB
/
iterator.js
File metadata and controls
97 lines (90 loc) · 3.15 KB
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
'use strict';
module.exports.get = function (collection, startPoint, depth) {
var friends = {};
if (depth > Object.keys(collection).length || depth == undefined) {
depth = Object.keys(collection).length;
}
if (startPoint in collection && depth != 0) {
var nextLevelQueue = [];
var currentLevelQueue = [];
var levelCounter = 0;
var friendsToAdd = [];
nextLevelQueue.push(startPoint);
while (levelCounter <= depth && nextLevelQueue.length > 0) {
levelCounter++;
currentLevelQueue = nextLevelQueue;
nextLevelQueue = [];
while (currentLevelQueue.length > 0) {
var currentPoint = currentLevelQueue.shift();
if (!(currentPoint in friends)) {
friends[currentPoint] = collection[currentPoint];
}
friendsToAdd = checkAndSortPersons(friends, startPoint,
collection[currentPoint]['friends']);
nextLevelQueue = nextLevelQueue.concat(friendsToAdd);
}
}
}
var stringifyResult = function (position) {
var result = {};
var personName = orderedFriendsNames[position];
result.name = personName;
result.phone = friends[personName]['phone'];
return (JSON.stringify(result));
};
var maleIterator = function (direction) {
var stringifiedPerson = direction();
while (stringifiedPerson !== null) {
var currentPerson = JSON.parse(stringifiedPerson);
if (friends[currentPerson.name]['gender'] === 'Мужской') {
return stringifiedPerson;
}
stringifiedPerson = direction();
}
return null;
};
var orderedFriendsNames = [];
for (var friendName in friends) {
orderedFriendsNames.push(friendName);
}
var positionToShow = 0;
return {
next: function (name) {
if (positionToShow + 1 >= orderedFriendsNames.length ||
Object.keys(friends).length == 0) {
return null;
}
if (name in friends) {
positionToShow = orderedFriendsNames.indexOf(name);
} else if (name !== undefined) {
return null;
} else {
positionToShow++;
}
return (stringifyResult(positionToShow));
},
prev: function () {
if (positionToShow - 1 < 0 || Object.keys(friends).length == 0) {
return null;
}
positionToShow--;
return (stringifyResult(positionToShow));
},
nextMale: function () {
return maleIterator(this.next);
},
prevMale: function () {
return maleIterator(this.prev);
}
};
};
function checkAndSortPersons(friends, startPoint, candidatesToAdd) {
var resultPersons = [];
candidatesToAdd = candidatesToAdd.sort();
for (var i = 0; i < candidatesToAdd.length; i++) {
if (!(candidatesToAdd[i] in friends)) {
resultPersons.push(candidatesToAdd[i]);
}
}
return resultPersons;
};