diff options
author | Jo-Philipp Wich <jo@mein.io> | 2022-10-04 20:22:50 +0200 |
---|---|---|
committer | Jo-Philipp Wich <jo@mein.io> | 2022-10-04 21:43:57 +0200 |
commit | 00965fabd5daa2be1991daf3ddf9f838ca534957 (patch) | |
tree | c622f10ca64b0a0f90600decd48ad50a8c17c6f7 /tests/custom/03_stdlib | |
parent | a5e59c9e93b9d435caa3fe786c745f0357bb3c0f (diff) |
lib: implement slice() function
Implement a new function `slice()` to complement the existing `splice()`
function and model it's semantics after the ES6 `Array.slice()` version.
Fixes: #106
Signed-off-by: Jo-Philipp Wich <jo@mein.io>
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 -- |