From c7eaee07940989dd905673615a7cb51cae453d33 Mon Sep 17 00:00:00 2001 From: j <0x006A@0x2620.org> Date: Tue, 9 Jul 2013 14:28:23 +0000 Subject: [PATCH] add Ox.queue --- source/Ox/js/Async.js | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/source/Ox/js/Async.js b/source/Ox/js/Async.js index acca402f..d7ac03e4 100644 --- a/source/Ox/js/Async.js +++ b/source/Ox/js/Async.js @@ -284,4 +284,44 @@ }; // FIXME: The above test with 10000 iterations blows the stack + + /*@ + Ox.queue + cached process queue, passed function is exectued in parallel and + results are cached based on all but last argument, + last argument is a callback that gets called with results + fn function + options + maxThreads number of concurrent threads + callback gets called with object containing duration, width, height + @*/ + Ox.queue = function(fn, options) { + var queue = [], + threads = 0; + + function process() { + var next = Math.min(queue.length, options.maxThreads-threads); + if (next) { + threads += next; + Ox.parallelForEach(queue.splice(0, next), function(args, index, array, done) { + fn.apply(this, args.slice(0, -1).concat(function(result) { + threads--; + args.slice(-1)[0](result); + done(); + })); + }, process); + } + } + + return Ox.cache(function() { + queue.push(Ox.toArray(arguments)); + process(); + }, { + async: true, + key: function(args) { + return JSON.stringify(args.slice(0, -1)); + } + }); + }; + }());