From 51dbccefce237a67f38f9a74e7fd4b8db76304a8 Mon Sep 17 00:00:00 2001 From: Florian Loitsch Date: Tue, 23 Jan 2024 08:18:05 +0100 Subject: [PATCH] Allow Task.group with 0 and 1 arguments. (#2056) --- lib/core/task.toit | 24 ++++++++++++++++++++++-- tests/task-group-test.toit | 13 ++++++++++--- 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/lib/core/task.toit b/lib/core/task.toit index 2279ae70d..39f09a16d 100644 --- a/lib/core/task.toit +++ b/lib/core/task.toit @@ -90,16 +90,36 @@ interface Task: return also throws. If $required is less than the number of $lambdas, the - method returns when $required tasks have completed. + method returns when $required tasks have completed. If $required + is equal to 0, the method returns immediately. + + # Examples + ``` + results := Task.group [ + :: 42, + :: 87, + ] + print results // => {0: 42, 1: 87}. + + results = Task.group --required=1 [ + // Due to the required=1, this lambda will be aborted, once + // the lambda returning 42 has finished. + :: sleep --ms=1_000; 87, + :: 42, + ] + print results // => { 1: 42 }. + ``` */ static group lambdas/List -> Map --required/int=lambdas.size: count ::= lambdas.size tasks ::= Array_ count results ::= {:} - if count < 2 or not (1 <= required <= count): + if not (0 <= required <= count): throw "Bad Argument" + if required == 0: return results + is-stopping/bool := false is-canceled/bool := false caught/Exception_? := null diff --git a/tests/task-group-test.toit b/tests/task-group-test.toit index 9223db412..a30ea59d0 100644 --- a/tests/task-group-test.toit +++ b/tests/task-group-test.toit @@ -31,20 +31,27 @@ run-case lambda/Lambda -> Task: return child test-simple: + expect-structural-equals {:} (Task.group []) + + expect-structural-equals { 0: 42 } (Task.group [ + :: 42, + ]) + expect-structural-equals { 0: 42, 1: 87 } (Task.group [ :: 42, :: 87, ]) test-bad-arguments: - expect-throw "Bad Argument": (Task.group []) - expect-throw "Bad Argument": (Task.group [ :: 42 ]) expect-throw "Bad Argument": (Task.group --required=-1 [ :: 42, :: 87 ]) - expect-throw "Bad Argument": (Task.group --required= 0 [ :: 42, :: 87 ]) expect-throw "Bad Argument": (Task.group --required= 3 [ :: 42, :: 87 ]) expect-throw "Bad Argument": (Task.group --required= 9 [ :: 42, :: 87 ]) test-required: + expect-structural-equals {:} (Task.group --required=0 [ + :: 42, + :: sleep --ms=1_000; 87, + ]) expect-structural-equals { 0: 42 } (Task.group --required=1 [ :: 42, :: sleep --ms=1_000; 87,