Groovy
  1. Groovy
  2. GROOVY-4164

A groovier way of iterate over dates/calendars: upTo() and downTo()

    Details

    • Type: New Feature New Feature
    • Status: Closed
    • Priority: Minor Minor
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 2.2.0-beta-2
    • Component/s: groovy-jdk
    • Labels:
      None

      Description

      Iterating over date intervals is currently possible using the following code:

      def start = new GregorianCalendar(2010, Calendar.JANUARY, 1).time
      def end = new GregorianCalendar(2010, Calendar.DECEMBER, 31).time
      
      def current = start
      while (current <= end) {
      	println current
      	current++
      }
      

      But following the style in which numbers are iterated, we can have a groovier code:

      start.upTo(end) {
      	println it
      }
      
      end.downTo(start) {
      	println it
      }
      

      Proposed implementation:

      	Date.metaClass {
      		upTo << { Date end, Closure c ->
      			def next = delegate
      			while (next <= end) {
      				c.call(next)
      				next++
      			}
      		}
      		downTo << { Date start, Closure c ->
      			def next = delegate
      			while (next >= start) {
      				c.call(next)
      				next--
      			}
      		}
      	}
      

        Activity

          People

          • Assignee:
            Pascal Schumacher
            Reporter:
            Alvaro Sanchez-Mariscal
          • Votes:
            1 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

            • Created:
              Updated:
              Resolved:

              Development