From 837d1fcd7f42bfaba684a40177e2dca9df4615e9 Mon Sep 17 00:00:00 2001 From: NoahLan <6995syu@163.com> Date: Mon, 4 Dec 2023 22:03:22 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20narr=20=E6=B7=BB=E5=8A=A0=E4=B8=80?= =?UTF-8?q?=E4=BA=9B=E8=81=9A=E5=90=88=EF=BC=88=E9=AB=98=E9=98=B6=EF=BC=89?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- narr/collection.go | 51 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/narr/collection.go b/narr/collection.go index 00a8561..f6d5660 100644 --- a/narr/collection.go +++ b/narr/collection.go @@ -425,3 +425,54 @@ func Map[T any, V any](list []T, mapFn func(obj T) (val V, find bool)) []V { func Column[T any, V any](list []T, mapFn func(obj T) (val V, find bool)) []V { return Map(list, mapFn) } + +// Every check all true in given slice +func Every[T any](list []T, fn func(T) bool) bool { + if len(list) == 0 { + return false + } + for _, t := range list { + if !fn(t) { + return false + } + } + return true +} + +// Some check some true in given slice +func Some[T any](list []T, fn func(T) bool) bool { + if len(list) == 0 { + return false + } + for _, t := range list { + if fn(t) { + return true + } + } + return false +} + +// Filter returns a new slice by given filter func +func Filter[T any](list []T, filterFn func(i int, currentValue T) bool) []T { + ret := make([]T, 0) + if list == nil { + return ret + } + + for i, v := range list { + if filterFn(i, v) { + ret = append(ret, v) + } + } + + return ret +} + +// Reduce all list item by given func +func Reduce[T any, M any](list []T, reduceFn func(total M, currentVal T, idx int) M, initialValue M) M { + ret := initialValue + for i, item := range list { + ret = reduceFn(ret, item, i) + } + return ret +}