Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe range operator in Groovy?

Tags:

range

groovy

Is there a safe range operator for Groovy?

For instance if I have,

[1,2,3][0..10]

Groovy will throw a java.lang.IndexOutOfBoundsException:

Is there a index safe way to access this range? Or do I always have to check the collection size prior to running a range?

like image 933
James McMahon Avatar asked Mar 23 '23 07:03

James McMahon


1 Answers

You can use take(n), which allows you to take up to a specific number of items, without error if there's too few in the collection:

def input = [1,2,3]
def result = input.take(10)
assert result == [1,2,3]

input = [1,2,3,4,5]
result = input.take(4)
assert result == [1,2,3,4]

If you need to start at an offset, you can use drop(n), which does not modify the original collection:

def input = [1,2,3,4,5]
def result = input.drop(2).take(2)
assert result == [3,4]

These are both safe against the size of the collection. If the list is too small in the last example, you may only have one or zero items in the collection.

like image 180
OverZealous Avatar answered Apr 06 '23 07:04

OverZealous