lazy-iterators.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. var fromArray = exports.fromArray = function(array) {
  2. var index = 0;
  3. var hasNext = function() {
  4. return index < array.length;
  5. };
  6. return new LazyIterator({
  7. hasNext: hasNext,
  8. next: function() {
  9. if (!hasNext()) {
  10. throw new Error("No more elements");
  11. } else {
  12. return array[index++];
  13. }
  14. }
  15. });
  16. };
  17. var LazyIterator = function(iterator) {
  18. this._iterator = iterator;
  19. };
  20. LazyIterator.prototype.map = function(func) {
  21. var iterator = this._iterator;
  22. return new LazyIterator({
  23. hasNext: function() {
  24. return iterator.hasNext();
  25. },
  26. next: function() {
  27. return func(iterator.next());
  28. }
  29. });
  30. };
  31. LazyIterator.prototype.filter = function(condition) {
  32. var iterator = this._iterator;
  33. var moved = false;
  34. var hasNext = false;
  35. var next;
  36. var moveIfNecessary = function() {
  37. if (moved) {
  38. return;
  39. }
  40. moved = true;
  41. hasNext = false;
  42. while (iterator.hasNext() && !hasNext) {
  43. next = iterator.next();
  44. hasNext = condition(next);
  45. }
  46. };
  47. return new LazyIterator({
  48. hasNext: function() {
  49. moveIfNecessary();
  50. return hasNext;
  51. },
  52. next: function() {
  53. moveIfNecessary();
  54. var toReturn = next;
  55. moved = false;
  56. return toReturn;
  57. }
  58. });
  59. };
  60. LazyIterator.prototype.first = function() {
  61. var iterator = this._iterator;
  62. if (this._iterator.hasNext()) {
  63. return iterator.next();
  64. } else {
  65. return null;
  66. }
  67. };
  68. LazyIterator.prototype.toArray = function() {
  69. var result = [];
  70. while (this._iterator.hasNext()) {
  71. result.push(this._iterator.next());
  72. }
  73. return result;
  74. };