Skip to content

Commit 77fc71a

Browse files
committed
Added reverse with test
1 parent efb64ed commit 77fc71a

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

js_array_method.go

+13
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,9 @@ func Some[T any](input []T, conditions interface{}) any {
122122
return len(output) > 0
123123
}
124124

125+
// conditions can be callback or a value
126+
// callback has two parameter one is element and another is index
127+
// callback must return true or false
125128
func Includes[T any](input []T, conditions interface{}) bool {
126129
result := Find(input, conditions)
127130

@@ -132,3 +135,13 @@ func Includes[T any](input []T, conditions interface{}) bool {
132135
}
133136
return true
134137
}
138+
139+
func Reverse[T any](input []T) []T {
140+
length := len(input) - 1
141+
var output []T
142+
for i := length; i >= 0; i-- {
143+
output = append(output, input[i])
144+
}
145+
146+
return output
147+
}

reverse_test.go

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package js_array_method
2+
3+
import "testing"
4+
5+
func TestReverse(t *testing.T) {
6+
users := []User{{Id: 10, Name: "John"}, {Id: 11, Name: "Doe"}, {Id: 12, Name: "Sabrina"}}
7+
8+
reversedUsers := Reverse(users)
9+
if reversedUsers[0].Id != 12 {
10+
t.Errorf("Expected %d received %d", 12, reversedUsers[0].Id)
11+
}
12+
13+
if reversedUsers[1].Id != 11 {
14+
t.Errorf("Expected %d received %d", 11, reversedUsers[0].Id)
15+
}
16+
}

0 commit comments

Comments
 (0)