summaryrefslogtreecommitdiffhomepage
path: root/tests/custom/03_stdlib/64_slice
blob: c8db3032278abc00a8b79553c906659339ca24ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
The `slice()` function returns a shallow copy of a portion of the source
array, as specified by the start and end offsets. The original array is
not modified.

If start is omitted or null, it defaults to `0`. If end is omitted or null,
it defaults to the length of the source array.

If either of the offsets is negative, it is treated as counting towards the
end of the array. If either value exceeds the array length, it is capped to
the length of the array.

Returns a new array containing the elements copied from the source array.

Returns `null` if the given input array value is not an array.


-- Testcase --
{%
	let arr = [ 1, 2, 3, 4, 5 ];

	print(join("\n", [
		// copy all items
		slice(arr),

		// copy item 3 onwards
		slice(arr, 3),

		// copy item 2 and 3
		slice(arr, 1, 3),

		// copy last two items
		slice(arr, -2),

		// copy items 3 and 4
		slice(arr, -3, -1)
	]), "\n");
%}
-- End --

-- Expect stdout --
[ 1, 2, 3, 4, 5 ]
[ 4, 5 ]
[ 2, 3 ]
[ 4, 5 ]
[ 3, 4 ]
-- End --


Supplying an invalid array will yield `null`.

-- Testcase --
{%
	printf("%.J\n", slice("not_an_array", 0, 1));
%}
-- End --

-- Expect stdout --
null
-- End --


Invalid, non-numeric offset or index values are treated as 0.

-- Testcase --
{%
	let arr = [ 1, 2, 3, 4, 5 ];

	print(join("\n", [
		slice(arr, "foo"),
		slice(arr, "foo", "bar")
	]), "\n");
%}
-- End --

-- Expect stdout --
[ 1, 2, 3, 4, 5 ]
[ ]
-- End --