Skip to content

Commit

Permalink
Allow Task.group with 0 and 1 arguments. (#2056)
Browse files Browse the repository at this point in the history
  • Loading branch information
floitsch authored Jan 23, 2024
1 parent 5c3c688 commit 51dbcce
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
24 changes: 22 additions & 2 deletions lib/core/task.toit
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 10 additions & 3 deletions tests/task-group-test.toit
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 51dbcce

Please sign in to comment.