Skip to content

Commit 0581d52

Browse files
committed
Add support for the method size(Object ...).
1 parent cacc617 commit 0581d52

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/main/java/com/github/underscore/$.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -619,6 +619,9 @@ public <K, V> Map<K, V> toMap() {
619619
}
620620

621621
public static int size(final Iterable<?> iterable) {
622+
if (iterable instanceof Collection) {
623+
return ((Collection) iterable).size();
624+
}
622625
int size;
623626
final Iterator<?> iterator = iterable.iterator();
624627
for (size = 0; iterator.hasNext(); size += 1) {
@@ -631,6 +634,10 @@ public int size() {
631634
return size(iterable);
632635
}
633636

637+
public static <E> int size(final E ... array) {
638+
return array.length;
639+
}
640+
634641
public static <E> List<List<E>> partition(final Iterable<E> iterable, final Predicate<E> pred) {
635642
final List<E> retVal1 = newArrayList();
636643
final List<E> retVal2 = newArrayList();

src/test/java/com/github/underscore/CollectionsTest.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1144,6 +1144,25 @@ public void size() {
11441144
assertEquals(4, resultObj);
11451145
final int resultChain = $.chain(asList(1, 2, 3, 4)).size();
11461146
assertEquals(4, resultChain);
1147+
final int[] array = new int[] {1, 2, 3, 4, 5, 6};
1148+
Iterable<Integer> iterable = new Iterable<Integer>() {
1149+
public Iterator<Integer> iterator() {
1150+
return new Iterator<Integer>() {
1151+
private int index;
1152+
public boolean hasNext() {
1153+
return array.length > index;
1154+
}
1155+
public Integer next() {
1156+
return array[index++];
1157+
}
1158+
public void remove() {
1159+
}
1160+
};
1161+
}
1162+
};
1163+
assertEquals(6, $.size(iterable));
1164+
assertEquals(5, $.size(new Integer[] {5, 4, 3, 2, 1}));
1165+
assertEquals(5, $.size(5, 4, 3, 2, 1));
11471166
}
11481167

11491168
/*

0 commit comments

Comments
 (0)