Skip to content

Commit

Permalink
Refine NamedTuple
Browse files Browse the repository at this point in the history
(cherry picked from commit 904347c)
  • Loading branch information
daniellansun committed Oct 26, 2024
1 parent 2b68428 commit 5dfb4a9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,24 @@ import groovy.transform.stc.POJO
@POJO
class NamedTuple<E> extends Tuple<E> {
private static final long serialVersionUID = -5067092453136522209L
private final Map<String, E> data = new LinkedHashMap<>()
private final Map<String, E> data

NamedTuple(List<E> elementList, List<String> nameList) {
super(elementList as E[])

int nameListSize = nameList.size()
final int nameListSize = nameList.size()
final int elementListSize = elementList.size()

if (nameListSize != elementListSize) {
throw new IllegalArgumentException("elements(size: $elementListSize) and names(size: $nameListSize) should have the same size")
}
if (nameListSize != new HashSet<>(nameList).size()) {
throw new IllegalArgumentException("names should be unique: $nameList")
}

for (int i = 0, n = nameListSize; i < n; i += 1) {
data = new LinkedHashMap<>((int) (nameListSize / 0.75) + 1)

for (int i = 0; i < nameListSize; i += 1) {
data.put(nameList.get(i), elementList.get(i))
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,15 @@ class NamedTupleTest {

assert err.toString().contains('names should be unique')
}

@Test
void testElementsAndNamesSizeMismatch() {
def err = shouldFail '''
import org.apache.groovy.ginq.provider.collection.runtime.NamedTuple
new NamedTuple([1, 2, 3], ['a', 'b'])
'''

assert err.toString().contains('elements(size: 3) and names(size: 2) should have the same size')
}
}

0 comments on commit 5dfb4a9

Please sign in to comment.