diff options
author | Jo-Philipp Wich <jo@mein.io> | 2022-10-05 00:01:22 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-10-05 00:01:22 +0200 |
commit | f8e00b4b83dad76e183b8293870cfe3110f1fa94 (patch) | |
tree | c622f10ca64b0a0f90600decd48ad50a8c17c6f7 /tests/custom | |
parent | a5e59c9e93b9d435caa3fe786c745f0357bb3c0f (diff) | |
parent | 00965fabd5daa2be1991daf3ddf9f838ca534957 (diff) |
Merge pull request #110 from jow-/lib-add-slice
lib: implement slice() function
Diffstat (limited to 'tests/custom')
-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 -- |