a zip code crypto-currency system good for red ONLY

forEachBail.js 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. module.exports = function forEachBail(array, iterator, callback) {
  6. if(array.length === 0) return callback();
  7. var currentPos = array.length;
  8. var currentResult;
  9. var done = [];
  10. for(var i = 0; i < array.length; i++) {
  11. var itCb = createIteratorCallback(i);
  12. iterator(array[i], itCb);
  13. if(currentPos === 0) break;
  14. }
  15. function createIteratorCallback(i) {
  16. return function() {
  17. if(i >= currentPos) return; // ignore
  18. var args = Array.prototype.slice.call(arguments);
  19. done.push(i);
  20. if(args.length > 0) {
  21. currentPos = i + 1;
  22. done = done.filter(function(item) {
  23. return item <= i;
  24. });
  25. currentResult = args;
  26. }
  27. if(done.length === currentPos) {
  28. callback.apply(null, currentResult);
  29. currentPos = 0;
  30. }
  31. };
  32. }
  33. };
  34. module.exports.withIndex = function forEachBailWithIndex(array, iterator, callback) {
  35. if(array.length === 0) return callback();
  36. var currentPos = array.length;
  37. var currentResult;
  38. var done = [];
  39. for(var i = 0; i < array.length; i++) {
  40. var itCb = createIteratorCallback(i);
  41. iterator(array[i], i, itCb);
  42. if(currentPos === 0) break;
  43. }
  44. function createIteratorCallback(i) {
  45. return function() {
  46. if(i >= currentPos) return; // ignore
  47. var args = Array.prototype.slice.call(arguments);
  48. done.push(i);
  49. if(args.length > 0) {
  50. currentPos = i + 1;
  51. done = done.filter(function(item) {
  52. return item <= i;
  53. });
  54. currentResult = args;
  55. }
  56. if(done.length === currentPos) {
  57. callback.apply(null, currentResult);
  58. currentPos = 0;
  59. }
  60. };
  61. }
  62. };