Finding

The asdk.algorithm.Finding class provides several static functions for finding elements within a collection. The example below demonstrates the use of these functions when searching for elements in an ArrayList. Note that, along with a collection, the detect, some, and every methods illustrated below also take a UnaryCondition as a parameter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import asdk.*;
import asdk.condition.*;

var list = new ArrayList( Array( 3, 7, 8, 2, -5, 8, 9, 44, -2 ) );

var firstNegative = Finding.detect( list, new NegativeNumber() );
trace( "firstNegative: " + firstNegative );
//displays firstNegative: -5 in output window

var firstPositive = Finding.detect( list, new PositiveNumber() );
trace( "firstPositive: " + firstPositive );
//displays firstPositive: 3 in output window

var firstValueGreaterThanTen = Finding.detect( list, new BindSecondCondition( new GreaterNumber(), 10 ) );
trace( "firstValueGreaterThanTen: " + firstValueGreaterThanTen );
//displays firstValueGreaterThanTen: 44 in output window

var containsNegative = Finding.some( list, new NegativeNumber() );
trace( "containsNegative: " + containsNegative );
//displays containsNegative: true in output window

var areAllNegative = Finding.every( list, new NegativeNumber() );
trace( "areAllNegative: " + areAllNegative );
//displays areAllNegative: false in output window

var containsPositive = Finding.some( list, new PositiveNumber() );
trace( "containsPositive: " + containsPositive );
//displays containsPositive: true in output window

var areAllPositive = Finding.every( list, new PositiveNumber() );
trace( "areAllPositive: " + areAllPositive );
//displays areAllPositive: false in output window

This example demonstrates using the detect, some and every methods of the Finding class. The detect method that is invoked on lines 6, 10, and 14 return the first element in the list that matches the unary condition. The most complicated invocation of detect on line 14 where the BindSecondCondition searched for the first number that is greater than ten, which in this case is 44.

The some and every methods return Boolean values depending on whether some or all of the elements in a collection match the specified unary condition. In this case, since the list contains some negative and some positive numbers, the calls to some (lines 18 and 26) return true, whereas the calls to every (lines 22 and 30) return false. The call to every will only return true when the unary condition that is executed returns true as would be the case if all the items were positive and the PositiveNumber condition was used.