Last active
August 29, 2015 14:04
-
-
Save AaronGhent/271d7b9805f1c5a82752 to your computer and use it in GitHub Desktop.
EmberArrayAsync.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @main EmberArrayAsync | |
*/ | |
/** | |
* forEachAsync iterates over a large array gradually. The function | |
* will process items in the array for a given number of ms, stop iterating for | |
* a given wait time, then proceed and wait until the iteration is complete. | |
* | |
* @method forEachAsync | |
*/ | |
var ASYNC_RUN_TIME = 200; | |
var ASYNC_WAIT_TIME = 200; | |
var forEachAsync = function(context, objects, eachFn, completeFn, runTime, wait) { | |
if (runTime === null) { | |
runTime = ASYNC_RUN_TIME; | |
} | |
if (wait === null) { | |
wait = ASYNC_WAIT_TIME; | |
} | |
if (!(Ember.Enumerable.detect(objects) || Ember.isArray(objects))) { | |
throw new TypeError("Must pass Ember.Enumerable to FilterWait"); | |
} | |
var getTime = function() { | |
if (Date.now) { | |
return Date.now(); | |
} else { | |
return new Date(); | |
} | |
}; | |
var processItems = function(items, process, callback) { | |
var itemsToProcess = Array.prototype.slice.call(items); | |
var i = null; | |
var loopFn = function() { | |
var start = getTime(); | |
process.call(context, itemsToProcess.shift(), (i !== null ? ++i : 0)); | |
while (itemsToProcess.length > 0 && getTime() - start < runTime) { | |
process.call(context, itemsToProcess.shift(), ++i); | |
} | |
if (itemsToProcess.length > 0) { | |
return Ember.run.later(context, loopFn, wait); | |
} else { | |
if ((callback !== null) && (callback.call !== null)) { | |
return callback.call(context); | |
} | |
} | |
}; | |
return Ember.run(context, loopFn); | |
}; | |
return processItems(objects, eachFn, completeFn); | |
}; | |
/** | |
* filterAsync iterates over a large array gradually. The function | |
* will process items in the array for a given number of ms, stop iterating for | |
* a given wait time, then proceed and wait until the iteration is complete. | |
* | |
* @method filterAsync | |
*/ | |
var filterAsync = function(context, objects, eachFn, completeFn, runTime, wait) { | |
var ret = []; | |
var filterFn = function(item, i) { | |
if (eachFn.call(context, item, i)) { | |
ret.push(item); | |
} | |
}; | |
var filterComplete = function() { | |
completeFn.call(context, ret); | |
}; | |
return forEachAsync(context, objects, filterFn, filterComplete, runTime, wait); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment