Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-4164

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

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • None
    • 2.2.0-beta-2
    • groovy-jdk
    • 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--
      			}
      		}
      	}
      

      Attachments

        Activity

          People

            pschumacher Pascal Schumacher
            alvaro.sanchez Alvaro Sanchez-Mariscal
            Votes:
            1 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: