From 7e2ecac38c625a00bd7417eee3436239425bd195 Mon Sep 17 00:00:00 2001 From: Jesse Bannon Date: Tue, 21 Nov 2023 17:03:55 -0800 Subject: [PATCH] array enumerate --- src/ytdl_sub/script/functions/array_functions.py | 12 +++++++++++- src/ytdl_sub/script/types/function.py | 3 ++- tests/unit/script/types/test_function.py | 6 ++---- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/ytdl_sub/script/functions/array_functions.py b/src/ytdl_sub/script/functions/array_functions.py index cc20f854..6b579bde 100644 --- a/src/ytdl_sub/script/functions/array_functions.py +++ b/src/ytdl_sub/script/functions/array_functions.py @@ -50,6 +50,16 @@ class ArrayFunctions: @staticmethod def array_apply(array: Array, lambda_function: Lambda) -> Array: """ - Reverse an Array. + Apply a lambda function on every element in the Array. """ return ResolvedArray([ResolvedArray([val]) for val in array.value]) + + @staticmethod + def array_enumerate(array: Array, lambda_function: Lambda) -> Array: + """ + Apply a lambda function on every element in the Array, where each arg + passed to the lambda function is ``idx, element`` as two separate args. + """ + return ResolvedArray( + [ResolvedArray([Integer(idx), val]) for idx, val in enumerate(array.value)] + ) diff --git a/src/ytdl_sub/script/types/function.py b/src/ytdl_sub/script/types/function.py index b8c1bb11..ccbee2e3 100644 --- a/src/ytdl_sub/script/types/function.py +++ b/src/ytdl_sub/script/types/function.py @@ -28,7 +28,8 @@ from ytdl_sub.script.types.variable import FunctionArgument from ytdl_sub.script.types.variable import Variable from ytdl_sub.script.types.variable_dependency import VariableDependency from ytdl_sub.script.utils.exception_formatters import FunctionArgumentsExceptionFormatter -from ytdl_sub.script.utils.exceptions import FunctionDoesNotExist, UNREACHABLE +from ytdl_sub.script.utils.exceptions import UNREACHABLE +from ytdl_sub.script.utils.exceptions import FunctionDoesNotExist from ytdl_sub.script.utils.exceptions import FunctionRuntimeException from ytdl_sub.script.utils.exceptions import UserThrownRuntimeError from ytdl_sub.script.utils.type_checking import FunctionInputSpec diff --git a/tests/unit/script/types/test_function.py b/tests/unit/script/types/test_function.py index 02efaae2..241053a9 100644 --- a/tests/unit/script/types/test_function.py +++ b/tests/unit/script/types/test_function.py @@ -127,8 +127,6 @@ class TestFunction: { "%times_three": "{%mul($0, 3)}", "%times_two": "{%mul($0, 2)}", - "wip": "{%array_apply([1, 2, 3], %if(False, %times_two, %times_three))}" + "wip": "{%array_apply([1, 2, 3], %if(False, %times_two, %times_three))}", } - ).resolve() == { - "wip": ResolvedArray([Integer(3), Integer(6), Integer(9)]) - } \ No newline at end of file + ).resolve() == {"wip": ResolvedArray([Integer(3), Integer(6), Integer(9)])}