Created
May 11, 2020 22:10
-
-
Save gbutt/21cdcff58e9089562584491c8300be6e to your computer and use it in GitHub Desktop.
Range Iterator for Salesforce. It is probably most useful in a batch class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RangeIterator implements Iterable<Integer> { | |
Integer start; | |
Integer stop; | |
public RangeIterator(Integer start, Integer stop) { | |
this.start = start; | |
this.stop = stop; | |
} | |
public Iterator<Integer> iterator() { | |
return new RangeIterable(start, stop); | |
} | |
public class RangeIterable implements Iterator<Integer> { | |
Integer start; | |
Integer stop; | |
Integer current; | |
public RangeIterable(Integer start, Integer stop) { | |
this.start = start; | |
this.stop = stop; | |
if (start == null || stop == null || start > stop) { | |
throw new GeneralException('invalid arguments'); | |
} | |
this.current = this.start; | |
} | |
public Boolean hasNext() { | |
return current <= stop; | |
} | |
public Integer next() { | |
return current++; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@IsTest | |
public class RangeIteratorTest { | |
@IsTest | |
static void it_should_iterate_over_range() { | |
RangeIterator iterator = new RangeIterator(0, 10); | |
Iterator<Integer> iterable = iterator.iterator(); | |
System.assertEquals(true, iterable.hasNext()); | |
System.assertEquals(0, iterable.next()); | |
System.assertEquals(true, iterable.hasNext()); | |
System.assertEquals(1, iterable.next()); | |
System.assertEquals(true, iterable.hasNext()); | |
System.assertEquals(2, iterable.next()); | |
System.assertEquals(true, iterable.hasNext()); | |
System.assertEquals(3, iterable.next()); | |
System.assertEquals(true, iterable.hasNext()); | |
System.assertEquals(4, iterable.next()); | |
System.assertEquals(true, iterable.hasNext()); | |
System.assertEquals(5, iterable.next()); | |
System.assertEquals(true, iterable.hasNext()); | |
System.assertEquals(6, iterable.next()); | |
System.assertEquals(true, iterable.hasNext()); | |
System.assertEquals(7, iterable.next()); | |
System.assertEquals(true, iterable.hasNext()); | |
System.assertEquals(8, iterable.next()); | |
System.assertEquals(true, iterable.hasNext()); | |
System.assertEquals(9, iterable.next()); | |
System.assertEquals(true, iterable.hasNext()); | |
System.assertEquals(10, iterable.next()); | |
System.assertEquals(false, iterable.hasNext()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment