diff --git a/flow.js b/flow.js index d46e521..e7a2d6a 100644 --- a/flow.js +++ b/flow.js @@ -4,7 +4,7 @@ * Сделано задание на звездочку * Реализованы методы mapLimit и filterLimit */ -exports.isStar = true; +exports.isStar = false; /** * Последовательное выполнение операций @@ -12,7 +12,20 @@ exports.isStar = true; * @param {Function} callback */ exports.serial = function (operations, callback) { - console.info(operations, callback); + if (!operations) { + callback(null, null); + } + var index = 0; + var cb = function (error, result) { + index++; + if (error || index === operations.length) { + callback(error, result); + } else { + operations[index](result, cb); + } + }; + operations[index](cb); + }; /** @@ -21,8 +34,33 @@ exports.serial = function (operations, callback) { * @param {Function} operation – функция для обработки элементов * @param {Function} callback */ + exports.map = function (items, operation, callback) { - console.info(items, operation, callback); + if (!items) { + callback(null, null); + } + var count = items.length; + var errorCallback = false; + var results = []; + var cb = function (index, err, result) { + if (err) { + errorCallback = true; + + return callback(err); + } + if (errorCallback) { + return; + } + count--; + results[index] = result; + if (count === 0) { + return callback(null, results); + } + }; + + items.forEach(function (item, index) { + operation(item, cb.bind(null, index)); + }); }; /** @@ -32,15 +70,33 @@ exports.map = function (items, operation, callback) { * @param {Function} callback */ exports.filter = function (items, operation, callback) { - console.info(items, operation, callback); + exports.map(items, operation, function (err, result) { + if (err) { + callback(err); + } + callback(null, items.filter(function (item, index) { + return result[index]; + })); + }); }; /** * Асинхронизация функций * @param {Function} func – функция, которой суждено стать асинхронной */ + exports.makeAsync = function (func) { - console.info(func); + return function () { + var args = [].slice.call(arguments); + var callback = args.pop(); + setTimeout(function () { + try { + callback(null, func.apply(null, args)); + } catch (error) { + callback(error); + } + }, 0); + }; }; /**