GithubHelp home page GithubHelp logo

collection's Introduction

collection

Collection包目标是用于替换golang原生的Slice,使用场景是在大量不追求极致性能,追求业务开发效能的场景。

Collection的使用手册线上地址:http://collection.funaio.cn/

你也可以通过类库直接在本地启动本地文档:(需要本机安装npm)

npm install 
npm run docs:dev

// 访问地址: http://localhost:2333/
版本 说明
v1.4.2 增加KeyByStrField方法,增加交集和并集函数 Union,Intersect
v1.4.0 增加三种新类型 uint32, uint, uint64, 增加GroupBy 和 Split 方法
v1.3.0 增加文档说明
1.2.0 增加对象指针数组,增加测试覆盖率, 增加ToInterfaces方法
1.1.2 增加一些空数组的判断,解决一些issue
1.1.1 对collection包进行了json解析和反解析的支持,对mix类型支持了SetField和RemoveFields的类型设置
1.1.0 增加了对int32的支持,增加了延迟加载,增加了Copy函数,增加了compare从ICollection传递到IMix,使用快排加速了Sort方法
1.0.1 第一次发布

go get github.com/jianfengye/[email protected]

Collection包目前支持的元素类型:int32, int, int64, uint32, uint, uint64, float32, float64, string, object, objectPoint

第一步:使用下列几个方法进行初始化Collection:

NewIntCollection(objs []int) *IntCollection

NewInt64Collection(objs []int64) *Int64Collection

NewInt32Collection(objs []int32) *Int32Collection

NewUIntCollection(objs []uint) *UIntCollection

NewUInt64Collection(objs []uint64) *UInt64Collection

NewUInt32Collection(objs []uint32) *UInt32Collection

NewFloat64Collection(objs []float64) *Float64Collection

NewFloat32Collection(objs []float32) *Float32Collection

NewStrCollection(objs []string) *StrCollection

NewObjCollection(objs interface{}) *ObjCollection

NewObjPointCollection(objs interface{}) *ObjPointCollection

第二步:你可以很方便使用ICollection的所有函数:

// ICollection 表示数组结构,有几种类型
type ICollection interface {
	// Err ICollection错误信息,链式调用的时候需要检查下这个error是否存在,每次调用之后都检查一下
	Err() error
	// SetErr 设置ICollection的错误信息
	SetErr(error) ICollection

	/*
		下面的方法对所有Collection都生效
	*/
	// NewEmpty 复制一份当前相同类型的ICollection结构,但是数据是空的
	NewEmpty(err ...error) ICollection
	// IsEmpty 判断是否是空数组
	IsEmpty() bool
	// IsNotEmpty 判断是否是空数组
	IsNotEmpty() bool
	// Append 放入一个元素到数组中,对所有Collection生效, 仅当item和Collection结构不一致的时候返回错误
	Append(item interface{}) ICollection
	// Remove 删除一个元素, 需要自类实现
	Remove(index int) ICollection
	// Insert 增加一个元素。
	Insert(index int, item interface{}) ICollection
	// Search 查找数据中是否包含,-1不包含,>=0 返回数组中元素下标,对所有Collection生效
	Search(item interface{}) int
	// Unique 过滤数组中重复的元素,仅对基础Collection生效
	Unique() ICollection
	// Filter 按照某个方法进行过滤, 保留符合的
	Filter(func(item interface{}, key int) bool) ICollection
	// Reject 按照某个方法进行过滤,去掉符合的
	Reject(func(item interface{}, key int) bool) ICollection
	// First 获取满足条件的第一个, 如果没有填写过滤条件,就获取所有的第一个
	First(...func(item interface{}, key int) bool) IMix
	// Last 获取满足条件的最后一个,如果没有填写过滤条件,就获取所有的最后一个
	Last(...func(item interface{}, key int) bool) IMix
	// Slice 获取数组片段,对所有Collection生效
	Slice(...int) ICollection
	// Index 获取某个下标,对所有Collection生效
	Index(i int) IMix
	// SetIndex 设置数组的下标为某个值
	SetIndex(i int, val interface{}) ICollection
	// Copy 复制当前数组
	Copy() ICollection
	// Count 获取数组长度,对所有Collection生效
	Count() int
	// Merge 将两个数组进行合并,参数的数据挂在当前数组中,返回当前数组,对所有Collection生效
	Merge(arr ICollection) ICollection

	// Each 每个元素都调用一次的方法
	Each(func(item interface{}, key int))
	// Map 每个元素都调用一次的方法, 并组成一个新的元素
	Map(func(item interface{}, key int) interface{}) ICollection
	// Reduce 合并一些元素,并组成一个新的元素
	Reduce(func(carry IMix, item IMix) IMix) IMix
	// Every 判断每个对象是否都满足, 如果collection是空,返回true
	Every(func(item interface{}, key int) bool) bool
	// ForPage 按照分页进行返回
	ForPage(page int, perPage int) ICollection
	// Nth 获取从索引offset开始为0,每n位值组成数组
	Nth(n int, offset int) ICollection
	// Pad 将数组填充到count个数,只能数值型生效
	Pad(count int, def interface{}) ICollection
	// Pop 从队列右侧弹出结构
	Pop() IMix
	// Push 推入元素
	Push(item interface{}) ICollection
	// Prepend 前面插入一个元素
	Prepend(item interface{}) ICollection
	// Random 随机获取一个元素
	Random() IMix
	// Reverse 倒置
	Reverse() ICollection
	// Shuffle 随机乱置
	Shuffle() ICollection
	// GroupBy 类scala groupby 设计, 根据某个函数分组
	GroupBy(func(interface{}, int) interface{}) map[interface{}]ICollection
	// Split 按照size个数进行分组
	Split(size int) []ICollection
	// DD 打印出当前数组结构
	DD()

	/*
		下面的方法对ObjCollection 和 ObjPointCollection 生效
	*/
	// Pluck 返回数组中对象的某个key组成的数组,仅对ObjectCollection生效, key为对象属性名称,必须为public的属性
	Pluck(key string) ICollection
	// SortBy 按照某个字段进行排序
	SortBy(key string) ICollection
	// SortByDesc 按照某个字段进行排序,倒序
	SortByDesc(key string) ICollection
	// KeyByStrField 根据某个字段为key,返回一个map, 要求key对应的field是string
	KeyByStrField(key string) (map[string]interface{}, error)

	/*
		下面的方法对基础Collection生效,但是ObjCollection一旦设置了Compare函数也生效
	*/
	// SetCompare 比较a和b,如果a>b, 返回1,如果a<b, 返回-1,如果a=b, 返回0
	// 设置比较函数,理论上所有Collection都能设置比较函数,但是强烈不建议基础Collection设置
	SetCompare(func(a interface{}, b interface{}) int) ICollection
	// GetCompare 获取比较函数
	GetCompare() func(a interface{}, b interface{}) int
	// Max 数组中最大的元素,仅对基础Collection生效, 可以传递一个比较函数
	Max() IMix
	// Min 数组中最小的元素,仅对基础Collection生效
	Min() IMix
	// Contains 判断是否包含某个元素,(并不进行定位),对基础Collection生效
	Contains(obj interface{}) bool
	// ContainsCount 判断包含某个元素的个数,返回0代表没有找到,返回正整数代表个数。必须设置compare函数
	ContainsCount(obj interface{}) int
	// Diff 比较两个数组,获取第一个数组不在第二个数组中的元素,组成新数组,仅对基础元素生效
	Diff(arr ICollection) ICollection
	// Sort 进行排序, 升序
	Sort() ICollection
	// SortDesc 进行排序,倒序
	SortDesc() ICollection
	// Join 进行拼接
	Join(split string, format ...func(item interface{}) string) string
	// Union 比较两个数组,获取两个数组并集,仅对基础元素生效
	Union (arr ICollection) ICollection
	// Intersect 比较两个数组,获取两个数组交集,仅对基础元素生效
	Intersect (arr ICollection) ICollection

	/*
		下面的方法对基础Collection生效
	*/
	// Avg 获取平均值
	Avg() IMix
	// Median 获取中位值
	Median() IMix
	// Mode 获取Mode值
	Mode() IMix
	// Sum 获取sum值
	Sum() IMix

	/*
		下面的方法对根据不同的对象,进行不同的调用转换
	*/
	// ToStrings 转化为golang原生的字符数组,仅对StrCollection生效
	ToStrings() ([]string, error)
	// ToInt64s 转化为golang原生的Int64数组,仅对Int64Collection生效
	ToInt64s() ([]int64, error)
	// ToInt32s 转化为golang原生的Int32数组,仅对Int32Collection生效
	ToInt32s() ([]int32, error)
	// ToInts 转化为golang原生的Int数组,仅对IntCollection生效
	ToInts() ([]int, error)
	// ToUInt64s 转化为golang原生的UInt64数组,仅对UInt64Collection生效
	ToUInt64s() ([]uint64, error)
	// ToUInt32s 转化为golang原生的UInt32数组,仅对UInt32Collection生效
	ToUInt32s() ([]uint32, error)
	// ToUInts 转化为golang原生的UInt数组,仅对UIntCollection生效
	ToUInts() ([]uint, error)
	// ToMixs 转化为obj数组
	ToMixs() ([]IMix, error)
	// ToFloat64s 转化为float64数组
	ToFloat64s() ([]float64, error)
	// ToFloat32s 转化为float32数组
	ToFloat32s() ([]float32, error)
	// ToInterfaces 转化为interface{} 数组
	ToInterfaces() ([]interface{}, error)
	// ToObjs 转化为objs{}数组
	ToObjs(interface{}) error

	// ToJson 转换为Json
	ToJson() ([]byte, error)
	// FromJson 从json数组转换
	FromJson([]byte) error
}

更多例子请参考: 使用手册

License

collection is licensed under Apache License.

Contributors

感谢下列作者的contributor. [Contribute].

author

有任何问题可直接github留言,或者联系作者:轩脉刃

xuanmairen

collection's People

Contributors

flc1125 avatar jianfengye avatar liangjfblue avatar monkeywithacupcake avatar nikolasviv avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

collection's Issues

Map函数能否提供像Java那种用法

有个需求是:我有一些id,我想让这些id通过map操作形成一个 []obj 的slice

type Person struct {
	ID        int
	TeacherID int
}

func main() {
	collection.NewObjCollection([]int{1, 2, 3}).Map(func(item interface{}, key int) interface{} {
		val := item.(int)
		return Person{
			ID:        1,
			TeacherID: val,
		}
	}).DD()
}

image

/[email protected]/abs_array.go:957 报超出索引错误

/[email protected]/abs_array.go:957 有时会报错;
Handler crashed with error runtime error: index out of range [4041] with length 4041
以下代码,如果这个[]string 一直变化 的话, 超长是不是就报错了?
func (arr *AbsCollection) ToStrings() ([]string, error) {
if arr.Err() != nil {
return nil, arr.Err()
}

ret := make([]string, arr.Count())
for i := 0; i < arr.Count(); i++ {
	t, err := arr.Index(i).ToString()
	if err != nil {
		return nil, err
	}
	ret[i] = t
}
return ret, nil

}

改成如下:?
func (arr *AbsCollection) ToStrings() ([]string, error) {
if arr.Err() != nil {
return nil, arr.Err()
}

size := arr.Count()
ret := make([]string, size)

for i := 0; i < size; i++ {
	t, err := arr.Index(i).ToString()
	if err != nil {
		return nil, err
	}
	ret[i] = t
}
return ret, nil

}

提升排序(sort) 效率

目前sort实现基于选择排序, 本身选择排序的复杂度 o(n * n), 作者在选择每层最大最小值增加了一层contain方法,实际又是一层循环,复杂度已经到 o(nnn)。

希望改进:
1、Icollection 增加复制构造.

2、 基于上边的条件,可以将排序换成快排。复杂度 o(n * log n)

请教一个线程安全问题

golang 并发对切片进行 append 会有线程安全问题,在使用 collection 的时候, 如需规避这个问题,是不是在每次调用 append 的时候都需要加锁呢,例如:

 var lock sync.Mutex

 lock.Lock()
 collection.append(...)
 lock.Unlock()

除了在 collection 中 使用 append 之外,其他的方法在使用的时候是不是也需要注意线程安全的问题,因为我好像没在源码中看到有任何使用到锁的地方。

map 方法 bug

image
根据第一个 字符 判断类型生成 数组 但是 obj 可能是[]interface 生成的是 是普通类型的。
还有这个方法没有continue 部分 func 返回 两个 参数 一个事data 一个是 bool bool判断是否continue

结构体数组如何实现筛选

[]TutorList{
TutorList{Pid:1, Realname:"陈老师", Remark:"", Grade:80}, 
TutorList{Pid:3, Realname:"陈老师", Remark:"", Grade:60}, 
TutorList{Pid:3, Realname:"陈老师", Remark:"", Grade:70}, 
TutorList{Pid:4, Realname:"陈老师", Remark:"", Grade:95}
}

现有上面的结构体数组,请问如何实现筛选?
例如 指定 TutorList.Pid=3 得到

[]TutorList{
TutorList{Pid:3, Realname:"陈老师", Remark:"", Grade:60}, 
TutorList{Pid:3, Realname:"陈老师", Remark:"", Grade:70}, 
}

希望添加KeyBy函数

希望实现laravel的keyby如下:
https://learnku.com/docs/laravel/5.8/collections/3916#method-keyby

$collection = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
]);
//根据结构体的字段组合新的数据返回
$keyed = $collection->keyBy('product_id');

/*
    [
        'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'],
        'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'],
    ]
*/

go希望返回map类型,key为 keyby的值字符串,value为结构体对象

type User struct {
	ID       int
	UserName string
	Age      int
}

user1 := User{ID: 1, UserName: "u1", Age: 18}
user2 := User{ID: 2, UserName: "u2", Age: 19}

collection.NewObjCollection([]User{user1, user2}).KeyBy("ID")
/*
"1": User{ID: 1, UserName: "u1", Age: 18},
"2": User{ID: 2, UserName: "u2", Age: 19}
*/

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.