Skip to content

Commit fedd958

Browse files
committed
[U] Sugar: subarray functions
1 parent 162f224 commit fedd958

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package org.hydev.mcpm.utils;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* Syntax sugar that java lacks
7+
*
8+
* @author Azalea (https://github.com/hykilpikonna)
9+
* @since 2022-10-30
10+
*/
11+
public class Sugar
12+
{
13+
/**
14+
* Subarray, behaves exactly like python's arr[start:end]
15+
*
16+
* @param arr Array
17+
* @param start Start (inclusive, negative numbers means (len - n))
18+
* @param end End (non-inclusive, negative numbers means (len - n))
19+
* @return Subarray
20+
* @param <T> Type of the array
21+
*/
22+
public static <T> T[] sub(T[] arr, int start, int end)
23+
{
24+
if (start < 0) start = arr.length + start;
25+
if (start < 0) start = 0;
26+
if (end < 0) end = arr.length + end;
27+
if (end < 0) end = 0;
28+
if (start > end) start = end;
29+
return Arrays.copyOfRange(arr, start, end);
30+
}
31+
32+
/**
33+
* Subarray from start, behaves exactly like python's arr[start:]
34+
*
35+
* @param arr Array
36+
* @param start Start (inclusive, negative numbers means (len - n))
37+
* @return Subarray
38+
* @param <T> Type of the array
39+
*/
40+
public static <T> T[] subFrom(T[] arr, int start)
41+
{
42+
return sub(arr, start, arr.length);
43+
}
44+
45+
/**
46+
* Subarray to end, behaves exactly like python's arr[:end]
47+
*
48+
* @param arr Array
49+
* @param end End (non-inclusive, negative numbers means (len - n))
50+
* @return Subarray
51+
* @param <T> Type of the array
52+
*/
53+
public static <T> T[] subTo(T[] arr, int end)
54+
{
55+
return sub(arr, 0, end);
56+
}
57+
}

0 commit comments

Comments
 (0)