Find accepts a function that returns a boolean, runs it over the array elements, and returns the first element on which it returned true. If there are any failed assertions in the predicate function, the element is skipped without causing test failure. If no elements were found, a failure is repor
(fn func(index int, value *Value) bool)
| 531 | // }) |
| 532 | // foundValue.IsEqual(101) // succeeds |
| 533 | func (a *Array) Find(fn func(index int, value *Value) bool) *Value { |
| 534 | opChain := a.chain.enter("Find()") |
| 535 | defer opChain.leave() |
| 536 | |
| 537 | if opChain.failed() { |
| 538 | return newValue(opChain, nil) |
| 539 | } |
| 540 | |
| 541 | if fn == nil { |
| 542 | opChain.fail(AssertionFailure{ |
| 543 | Type: AssertUsage, |
| 544 | Errors: []error{ |
| 545 | errors.New("unexpected nil function argument"), |
| 546 | }, |
| 547 | }) |
| 548 | return newValue(opChain, nil) |
| 549 | } |
| 550 | |
| 551 | for index, element := range a.value { |
| 552 | found := false |
| 553 | |
| 554 | func() { |
| 555 | valueChain := opChain.replace("Find[%d]", index) |
| 556 | defer valueChain.leave() |
| 557 | |
| 558 | valueChain.setRoot() |
| 559 | valueChain.setSeverity(SeverityLog) |
| 560 | |
| 561 | if fn(index, newValue(valueChain, element)) && !valueChain.treeFailed() { |
| 562 | found = true |
| 563 | } |
| 564 | }() |
| 565 | |
| 566 | if found { |
| 567 | return newValue(opChain, element) |
| 568 | } |
| 569 | } |
| 570 | |
| 571 | opChain.fail(AssertionFailure{ |
| 572 | Type: AssertValid, |
| 573 | Actual: &AssertionValue{a.value}, |
| 574 | Errors: []error{ |
| 575 | errors.New("expected: at least one array element matches predicate"), |
| 576 | }, |
| 577 | }) |
| 578 | |
| 579 | return newValue(opChain, nil) |
| 580 | } |
| 581 | |
| 582 | // FindAll accepts a function that returns a boolean, runs it over the array |
| 583 | // elements, and returns all the elements on which it returned true. |