mirror of
https://github.com/rjNemo/underscore
synced 2026-06-06 02:26:42 +00:00
docs: update examples
This commit is contained in:
parent
f05fb70292
commit
a0944476b9
2 changed files with 13 additions and 13 deletions
17
README.md
17
README.md
|
|
@ -11,6 +11,12 @@ It is mostly a port from the `underscore.js` library based on generics brought b
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
|
Install the library using
|
||||||
|
|
||||||
|
```shell
|
||||||
|
go get github.com/rjNemo/underscore
|
||||||
|
```
|
||||||
|
|
||||||
Please check out the [examples](examples) to see how to use the library.
|
Please check out the [examples](examples) to see how to use the library.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
|
@ -24,14 +30,11 @@ import (
|
||||||
func main() {
|
func main() {
|
||||||
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
|
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
|
||||||
// filter even numbers from the slice
|
// filter even numbers from the slice
|
||||||
isEven := func(n int) bool { return n%2 == 0 }
|
evens := u.Filter(numbers, func(n int) bool { return n%2 == 0 })
|
||||||
evens := u.Filter(numbers, isEven)
|
|
||||||
// square every number in the slice
|
// square every number in the slice
|
||||||
toSquare := func(n int) int { return n * n }
|
squares := u.Map(evens, func(n int) int { return n * n })
|
||||||
squares := u.Map(evens, toSquare)
|
// reduce to the sum
|
||||||
// reduce to the sum
|
res := u.Reduce(squares, func(n, acc int) int { return n + acc }, 0)
|
||||||
sum := func(n, acc int) int { return n + acc }
|
|
||||||
res := u.Reduce(squares, sum, 0)
|
|
||||||
|
|
||||||
fmt.Println(res) // 120
|
fmt.Println(res) // 120
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,14 +9,11 @@ import (
|
||||||
func main() {
|
func main() {
|
||||||
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
|
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
|
||||||
// filter even numbers from the slice
|
// filter even numbers from the slice
|
||||||
isEven := func(n int) bool { return n%2 == 0 }
|
evens := u.Filter(numbers, func(n int) bool { return n%2 == 0 })
|
||||||
evens := u.Filter(numbers, isEven)
|
|
||||||
// square every number in the slice
|
// square every number in the slice
|
||||||
toSquare := func(n int) int { return n * n }
|
squares := u.Map(evens, func(n int) int { return n * n })
|
||||||
squares := u.Map(evens, toSquare)
|
|
||||||
// reduce to the sum
|
// reduce to the sum
|
||||||
sum := func(n, acc int) int { return n + acc }
|
res := u.Reduce(squares, func(n, acc int) int { return n + acc }, 0)
|
||||||
res := u.Reduce(squares, sum, 0)
|
|
||||||
|
|
||||||
fmt.Println(res)
|
fmt.Println(res)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue