Skip to content

Commit 20ee60b

Browse files
committed
Implement list Map
1 parent e9d404d commit 20ee60b

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

list/persistent.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,10 @@ type PersistentList interface {
6969
// FindIndex applies the predicate function to the list and returns the
7070
// index of the first item which matches or -1 if there is no match.
7171
FindIndex(func(interface{}) bool) int
72+
73+
// Map applies the function to each entry in the list and returns the
74+
// resulting slice.
75+
Map(func(interface{}) interface{}) []interface{}
7276
}
7377

7478
type emptyList struct{}
@@ -133,6 +137,12 @@ func (e *emptyList) FindIndex(func(interface{}) bool) int {
133137
return -1
134138
}
135139

140+
// Map applies the function to each entry in the list and returns the resulting
141+
// slice.
142+
func (e *emptyList) Map(func(interface{}) interface{}) []interface{} {
143+
return nil
144+
}
145+
136146
type list struct {
137147
head interface{}
138148
tail PersistentList
@@ -237,3 +247,9 @@ func (l *list) FindIndex(pred func(interface{}) bool) int {
237247
idx += 1
238248
}
239249
}
250+
251+
// Map applies the function to each entry in the list and returns the resulting
252+
// slice.
253+
func (l *list) Map(f func(interface{}) interface{}) []interface{} {
254+
return append(l.tail.Map(f), f(l.head))
255+
}

list/persistent_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,3 +276,14 @@ func TestLength(t *testing.T) {
276276
l = l.Add("bar").Add("baz")
277277
assert.Equal(uint(3), l.Length())
278278
}
279+
280+
func TestMap(t *testing.T) {
281+
assert := assert.New(t)
282+
f := func(x interface{}) interface{} {
283+
return x.(int) * x.(int)
284+
}
285+
assert.Nil(Empty.Map(f))
286+
287+
l := Empty.Add(1).Add(2).Add(3).Add(4)
288+
assert.Equal([]interface{}{1, 4, 9, 16}, l.Map(f))
289+
}

0 commit comments

Comments
 (0)