forked from urfu-2016/javascript-task-8
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflow.js
163 lines (142 loc) · 5.05 KB
/
flow.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
'use strict';
/**
* Сделано задание на звездочку
* Реализованы методы mapLimit и filterLimit
*/
exports.isStar = true;
/**
* Последовательное выполнение операций
* @param {Function[]} operations – функции для выполнения
* @param {Function} callback
*/
exports.serial = function (operations, callback) {
var operationIndex = 0;
var operationsLen = operations.length - 1;
function serialCallback(error, data) {
if (!error && operationIndex !== operationsLen) {
if (data) {
operations[++operationIndex](data, serialCallback);
} else {
operations[++operationIndex](serialCallback);
}
} else {
callback(error, data);
}
}
if (operationsLen >= 0) {
operations[0](serialCallback);
} else {
callback(null, null);
}
};
/**
* Параллельная обработка элементов
* @param {Array} items – элементы для итерации
* @param {Function} operation – функция для обработки элементов
* @param {Function} callback
*/
exports.map = function (items, operation, callback) {
exports.mapLimit(items, Infinity, operation, callback);
};
/**
* Параллельная фильтрация элементов
* @param {Array} items – элементы для фильтрация
* @param {Function} operation – функция фильтрации элементов
* @param {Function} callback
*/
exports.filter = function (items, operation, callback) {
exports.filterLimit(items, Infinity, operation, callback);
};
/**
* Асинхронизация функций
* @param {Function} func – функция, которой суждено стать асинхронной
* @returns {Function} func - функция попадающая в очередь событий
*/
exports.makeAsync = function (func) {
return function () {
setTimeout(function (args) {
var cb = args.pop();
try {
cb(null, func.apply(null, args));
} catch (err) {
cb(err, null);
}
}, 0, Array.prototype.slice.call(arguments));
};
};
/**
* Параллельная обработка элементов с ограничением
* @star
* @param {Array} items – элементы для итерации
* @param {Number} limit – максимальное количество выполняемых параллельно операций
* @param {Function} operation – функция для обработки элементов
* @param {Function} callback
*/
exports.mapLimit = function (items, limit, operation, callback) {
if (items.length === 0) {
callback(null, []);
return;
}
var operationsKeeper = items.map(function (item, operationIndex) {
return { 'operation': operation.bind(null, item), 'operationIndex': operationIndex };
});
var operationsQueue = operationsKeeper.slice();
var doneCount = 0;
var activeCount = 0;
var resultDict = {};
var isError = false;
function execOperation(operationIndex, error, data) {
if (error && !isError) {
callback(error, data);
isError = true;
return;
}
resultDict[operationIndex] = data;
doneCount++;
activeCount--;
if (doneCount === items.length) {
var result = [];
for (var i = 0; i < items.length; i++) {
result.push(resultDict[i]);
}
callback(error, result);
return;
}
if (operationsQueue.length) {
operationsQueue.splice(0, limit).forEach(function (keeper) {
handleOperation(keeper);
});
}
}
function handleOperation(keeper) {
if (activeCount < limit) {
activeCount++;
keeper.operation(execOperation.bind(null, keeper.operationIndex));
} else {
operationsQueue.unshift(keeper);
}
}
operationsQueue.splice(0, limit).forEach(function (keeper) {
handleOperation(keeper);
});
};
/**
* Параллельная фильтрация элементов с ограничением
* @star
* @param {Array} items – элементы для итерации
* @param {Number} limit – максимальное количество выполняемых параллельно операций
* @param {Function} operation – функция для обработки элементов
* @param {Function} callback
*/
exports.filterLimit = function (items, limit, operation, callback) {
this.mapLimit(items, limit, operation, function (err, data) {
if (err) {
callback(err);
} else {
data = items.filter(function (item, operationIndex) {
return data[operationIndex];
});
callback(null, data);
}
});
};