Skip to content

Commit a109150

Browse files
committed
Add support for $.get(list, index), $.get(index), $.set(list, index,
value) and $.set(index, value) methods.
1 parent 80b1bcc commit a109150

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2604,6 +2604,25 @@ public T elementAt(final int index) {
26042604
return elementAt((List<T>) value(), index);
26052605
}
26062606

2607+
public static <T> T get(final List<T> list, final int index) {
2608+
return elementAt(list, index);
2609+
}
2610+
2611+
@SuppressWarnings("unchecked")
2612+
public T get(final int index) {
2613+
return elementAt((List<T>) value(), index);
2614+
}
2615+
2616+
public static <T> Tuple<T, List<T>> set(final List<T> list, final int index, final T value) {
2617+
final List<T> newList = newArrayList(list);
2618+
return Tuple.create(newList.set(index, value), newList);
2619+
}
2620+
2621+
@SuppressWarnings("unchecked")
2622+
public Tuple<T, List<T>> set(final int index, final T value) {
2623+
return set((List<T>) value(), index, value);
2624+
}
2625+
26072626
public static <T> T elementAtOrElse(final List<T> list, final int index, T defaultValue) {
26082627
try {
26092628
return list.get(index);

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,32 @@ public void elementAt() {
208208
assertEquals(2, new $<Integer>(asList(1, 2, 3)).elementAt(1).intValue());
209209
}
210210

211+
/*
212+
var arr = [ 1, 2, 3 ]
213+
_.get(arr, 1) // => 2
214+
*/
215+
@Test
216+
@SuppressWarnings("unchecked")
217+
public void get() {
218+
assertEquals(2, $.<Integer>get(asList(1, 2, 3), 1).intValue());
219+
assertEquals(2, new $<Integer>(asList(1, 2, 3)).get(1).intValue());
220+
}
221+
222+
/*
223+
var arr = [ 1, 2, 3 ]
224+
_.set(arr, 1, 100) // => 2
225+
*/
226+
@Test
227+
@SuppressWarnings("unchecked")
228+
public void set() {
229+
Tuple<Integer, List<Integer>> result = $.<Integer>set(asList(1, 2, 3), 1, 100);
230+
assertEquals(2, result.fst().intValue());
231+
assertEquals(100, $.<Integer>get(result.snd(), 1).intValue());
232+
Tuple<Integer, List<Integer>> result2 = new $<Integer>(asList(1, 2, 3)).set(2, 200);
233+
assertEquals(3, result2.fst().intValue());
234+
assertEquals(200, result2.snd().get(2).intValue());
235+
}
236+
211237
/*
212238
var arr = [ 1, 2, 3 ]
213239
_.elementAt(arr, 3) // => IndexOutOfBoundsException

0 commit comments

Comments
 (0)