From 00965fabd5daa2be1991daf3ddf9f838ca534957 Mon Sep 17 00:00:00 2001
From: Jo-Philipp Wich <jo@mein.io>
Date: Tue, 4 Oct 2022 20:22:50 +0200
Subject: 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>
---
 tests/custom/03_stdlib/64_slice | 78 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 78 insertions(+)
 create mode 100644 tests/custom/03_stdlib/64_slice

(limited to 'tests/custom/03_stdlib')

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 --
-- 
cgit v1.2.3