diff options
Diffstat (limited to 'tests/custom/03_stdlib')
-rw-r--r-- | tests/custom/03_stdlib/64_slice | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/tests/custom/03_stdlib/64_slice b/tests/custom/03_stdlib/64_slice new file mode 100644 index 0000000..c8db303 --- /dev/null +++ b/tests/custom/03_stdlib/64_slice @@ -0,0 +1,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 -- |