//Lazy array processing /** * Input parameters * params = { * outerFuntion : function(array, start, stop), * mainArray: [] * startIndex: Int, * stepRange Int, * timeOut: Int, * callback: function() *} */ var lazyProcessing = function(params) { var innerFunction = (function(_) { return function() { var arrayLength = _.mainArray.length, stopIndex = _.startIndex + _.stepRange; if(arrayLength < stopIndex) { _.outerFunction( _.mainArray, _.startIndex, arrayLength - _.startIndex); if(_.callback != undefined) { _.callback(); } return; } else { _.outerFunction( _.mainArray, _.startIndex, stopIndex); _.startIndex += _.stepRange; lazyProcessing(_); } } })(params); setTimeout(innerFunction, params.timeOut); }; //Outer function works with mainArray in given range var func = function(mainArray, start, stop) { //TODO: this should be everything you want to do with elements of for (var i = start; i < stop; ++i) { // do something } };
//Test array var test = []; for(var i = 0; i < 100000; ++i) { test[i] = i; } //Lazy array processing /* params = { outerFuntion : function(array, start, stop), mainArray: [] startIndex: Int, stepRange Int, timeOut: Int, callback: function() } */ var lazyProcessing = function(params) { var _params = params; var innerFunction = (function(_) { return function() { var arrayLength = _.mainArray.length, stopIndex = _.startIndex + _.stepRange; if(arrayLength < stopIndex) { _.outerFunction( .mainArray, _.startIndex, arrayLength - _.startIndex); if(_.callback != undefined) { _.callback(); } return; } else { _.outerFunction( _.mainArray, _.startIndex, stopIndex); _.startIndex += _.stepRange; lazyProcessing(_); } } })(_params); setTimeout(innerFunction, _params.timeOut); }; //Test function works with array var func = function(mainArray, start, stop) { //TODO: this should be everything //you want to do with elements of mainArray var _t = 0; for (var i = start; i < stop; ++i) { mainArray[i] = mainArray[i]+2; _t += mainArray[i]; } }; lazyProcessing({ outerFunction: func, mainArray: test, startIndex: 0, stepRange: 1000, timeOut: 100, callback: function() { alert("Done"); } });
/* example of use var arr = ['masha','nadya', 'elena']; iterate_async(arr, function (el, index, arr) { console.log(el + ' is #' + (index + 1)); }, 99); */ function iterate_async (arr, callback, timeout) { var item_to_proceed; item_to_proceed = 0; (function proceed_next () { if (item_to_proceed < arr.length) { setTimeout(function () { callback.call(arr, arr[item_to_proceed], item_to_proceed, arr); item_to_proceed += 1; proceed_next(); }, timeout || 50); } }()); }
Source: https://habr.com/ru/post/151155/
All Articles