From b3374cb4d5e18ebcc564761c0a88cc9ef14f1b79 Mon Sep 17 00:00:00 2001 From: Jesse Bannon Date: Fri, 19 Jan 2024 00:51:44 -0800 Subject: [PATCH] [DEV] `%map_extend` scripting function (#906) * [DEV] `%map_extend` scripting function * lint --- .../scripting/scripting_functions.rst | 8 ++++++++ src/ytdl_sub/script/functions/map_functions.py | 14 ++++++++++++++ tests/unit/script/functions/test_map_functions.py | 12 ++++++++++++ 3 files changed, 34 insertions(+) diff --git a/docs/source/config_reference/scripting/scripting_functions.rst b/docs/source/config_reference/scripting/scripting_functions.rst index 9302e10b..db773b17 100644 --- a/docs/source/config_reference/scripting/scripting_functions.rst +++ b/docs/source/config_reference/scripting/scripting_functions.rst @@ -415,6 +415,14 @@ map_enumerate Apply a lambda function on the Map, where each arg passed to the lambda function is ``idx, key, value`` as three separate args. +map_extend +~~~~~~~~~~ +:spec: ``map_extend(maps: Map, ...) -> Map`` + +:description: + Return maps combined in the order from left-to-right. Duplicate keys will use the + right-most map's value. + map_get ~~~~~~~ :spec: ``map_get(mapping: Map, key: AnyArgument, default: Optional[AnyArgument]) -> AnyArgument`` diff --git a/src/ytdl_sub/script/functions/map_functions.py b/src/ytdl_sub/script/functions/map_functions.py index b34fa611..6d93d31b 100644 --- a/src/ytdl_sub/script/functions/map_functions.py +++ b/src/ytdl_sub/script/functions/map_functions.py @@ -1,3 +1,4 @@ +from typing import Dict from typing import Optional from ytdl_sub.script.types.array import Array @@ -66,6 +67,19 @@ class MapFunctions: ) return mapping.value[key] + @staticmethod + def map_extend(*maps: Map) -> Map: + """ + :description: + Return maps combined in the order from left-to-right. Duplicate keys will use the + right-most map's value. + """ + output_dict: Dict = {} + for map_i in maps: + output_dict |= map_i.value + + return Map(output_dict) + @staticmethod def map_get_non_empty(mapping: Map, key: AnyArgument, default: AnyArgument) -> AnyArgument: """ diff --git a/tests/unit/script/functions/test_map_functions.py b/tests/unit/script/functions/test_map_functions.py index 709445e6..befc611e 100644 --- a/tests/unit/script/functions/test_map_functions.py +++ b/tests/unit/script/functions/test_map_functions.py @@ -138,3 +138,15 @@ class TestMapFunctions: FunctionRuntimeException, match="Tried and failed to cast Integer as a Map" ): single_variable_output("{%map(1)}") + + def test_map_extend(self): + output = single_variable_output( + """{ + %map_extend( + {'key': 'value', 1: 3}, + {'key': 'override'} + {'new': [1, 2]} + ) + }""" + ) + assert output == {"key": "override", "new": [1, 2], 1: 3}