diff --git a/lib/date.js b/lib/date.js index 27b35a54..69a37a77 100644 --- a/lib/date.js +++ b/lib/date.js @@ -194,6 +194,10 @@ CronDate.prototype.toDate = function() { return this._date.toDate(); }; +CronDate.prototype.valueOf = function() { + return this._date.valueOf(); +} + CronDate.prototype.isLastDayOfMonth = function() { var newDate = this._date.clone(); //next day diff --git a/lib/expression.js b/lib/expression.js index 78eebace..5721b3b0 100644 --- a/lib/expression.js +++ b/lib/expression.js @@ -606,6 +606,27 @@ CronExpression.prototype._findSchedule = function _findSchedule (reverse) { return currentDate; }; +if (Symbol && Symbol.iterator) { + /** + * ES6 iterable + * + * @public + * @return {Object} + */ + CronExpression.prototype[Symbol.iterator] = function() { + var self = this + return { + next: function() { + var schedule = self._findSchedule(); + return { + value: schedule, + done: !self.hasNext() + } + } + }; + } +} + /** * Find next suitable date * diff --git a/lib/index.d.ts b/lib/index.d.ts index e2f12853..a60d060f 100644 --- a/lib/index.d.ts +++ b/lib/index.d.ts @@ -47,6 +47,7 @@ declare class CronDate { getTime(): number toString(): string toDate(): Date + valueOf(): number } interface ParserOptions { @@ -58,7 +59,7 @@ interface ParserOptions { tz?: string } -declare class CronExpression { +declare class CronExpression implements Iterable { constructor(fields: {}, options: {}) /** Find next suitable date */ @@ -79,6 +80,8 @@ declare class CronExpression { /** Parse input expression (async) */ parse(expression: string, options?: ParserOptions, callback?: () => any): CronExpression + + [Symbol.iterator](): Iterator } interface StringResult { diff --git a/test/expression.js b/test/expression.js index 1393225f..2f428603 100644 --- a/test/expression.js +++ b/test/expression.js @@ -1363,6 +1363,28 @@ test('should work with both dayOfMonth and nth occurence of dayOfWeek', function t.end(); }); +test('should be iterable', function(t) { + var options = { + currentDate: new CronDate('Wed, 26 Dec 2012 14:38:53'), + startDate: new CronDate('Wed, 26 Dec 2012 12:40:00'), + endDate: new CronDate('Wed, 26 Dec 2012 15:40:00') + }; + + var interval = CronExpression.parse('*/20 * * * *', options); + t.ok(interval, 'Interval parsed'); + + var iterated = [...interval].map((date) => date.toJSON()); + var expected = [ + "2012-12-26T14:40:00.000Z", + "2012-12-26T15:00:00.000Z", + "2012-12-26T15:20:00.000Z", + ]; + + t.deepEqual(expected, iterated); + + t.end(); +}) + test('should error when passed invalid occurence value', function(t) { var expressions = [ '0 0 0 ? * 1#',