git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/validate/arrays_test.go (about)

     1  package validate
     2  
     3  import "testing"
     4  
     5  func TestEach(t *testing.T) {
     6  	// TODO Maybe refactor?
     7  	t.Parallel()
     8  	acc := 0
     9  	data := []interface{}{1, 2, 3, 4, 5}
    10  	var fn Iterator = func(value interface{}, index int) {
    11  		acc = acc + value.(int)
    12  	}
    13  	Each(data, fn)
    14  	if acc != 15 {
    15  		t.Errorf("Expected Each(..) to be %v, got %v", 15, acc)
    16  	}
    17  }
    18  
    19  func TestMap(t *testing.T) {
    20  	// TODO Maybe refactor?
    21  	t.Parallel()
    22  	data := []interface{}{1, 2, 3, 4, 5}
    23  	var fn ResultIterator = func(value interface{}, index int) interface{} {
    24  		return value.(int) * 3
    25  	}
    26  	result := Map(data, fn)
    27  	for i, d := range result {
    28  		if d != fn(data[i], i) {
    29  			t.Errorf("Expected Map(..) to be %v, got %v", fn(data[i], i), d)
    30  		}
    31  	}
    32  }
    33  
    34  func TestFind(t *testing.T) {
    35  	// TODO Maybe refactor?
    36  	t.Parallel()
    37  	findElement := 96
    38  	data := []interface{}{1, 2, 3, 4, findElement, 5}
    39  	var fn1 ConditionIterator = func(value interface{}, index int) bool {
    40  		return value.(int) == findElement
    41  	}
    42  	var fn2 ConditionIterator = func(value interface{}, index int) bool {
    43  		value, _ = value.(string)
    44  		return value == "govalidator"
    45  	}
    46  	val1 := Find(data, fn1)
    47  	val2 := Find(data, fn2)
    48  	if val1 != findElement {
    49  		t.Errorf("Expected Find(..) to be %v, got %v", findElement, val1)
    50  	}
    51  	if val2 != nil {
    52  		t.Errorf("Expected Find(..) to be %v, got %v", nil, val2)
    53  	}
    54  }
    55  
    56  func TestFilter(t *testing.T) {
    57  	// TODO Maybe refactor?
    58  	t.Parallel()
    59  	data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    60  	answer := []interface{}{2, 4, 6, 8, 10}
    61  	var fn ConditionIterator = func(value interface{}, index int) bool {
    62  		return value.(int)%2 == 0
    63  	}
    64  	result := Filter(data, fn)
    65  	for i := range result {
    66  		if result[i] != answer[i] {
    67  			t.Errorf("Expected Filter(..) to be %v, got %v", answer[i], result[i])
    68  		}
    69  	}
    70  }
    71  
    72  func TestCount(t *testing.T) {
    73  	// TODO Maybe refactor?
    74  	t.Parallel()
    75  	data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    76  	count := 5
    77  	var fn ConditionIterator = func(value interface{}, index int) bool {
    78  		return value.(int)%2 == 0
    79  	}
    80  	result := Count(data, fn)
    81  	if result != count {
    82  		t.Errorf("Expected Count(..) to be %v, got %v", count, result)
    83  	}
    84  }