diff options
author | chai <chaifix@163.com> | 2021-11-15 11:54:17 +0800 |
---|---|---|
committer | chai <chaifix@163.com> | 2021-11-15 11:54:17 +0800 |
commit | 30f2f46474bf4eda5f10d4c64a07cde01d469f66 (patch) | |
tree | 6ff2ed3262037b3c9bae2d2b9059a1d65773f31c /Data/BuiltIn/Libraries/containers/vector.lua | |
parent | 4c36bed53fe63ae6056730b3ecad2573f03d88f8 (diff) |
*rename DefaultContent -> BuiltIn
Diffstat (limited to 'Data/BuiltIn/Libraries/containers/vector.lua')
-rw-r--r-- | Data/BuiltIn/Libraries/containers/vector.lua | 122 |
1 files changed, 122 insertions, 0 deletions
diff --git a/Data/BuiltIn/Libraries/containers/vector.lua b/Data/BuiltIn/Libraries/containers/vector.lua new file mode 100644 index 0000000..0b349ce --- /dev/null +++ b/Data/BuiltIn/Libraries/containers/vector.lua @@ -0,0 +1,122 @@ +--- +--- Generated by EmmyLua(https://github.com/EmmyLua) +--- Created by Dee. +--- DateTime: 2019/3/7 14:00 +--- 快速遍历修改,低效的增删 +--- + +vector = vector or {} + +function vector.create() + local t = {} + + + ---尾添加元素(高效) + function t:add(v) + rawset(self, #self + 1, v) + end + + ---插入(低效) + ---@param k 位置 + ---@param v 值 + function t:insert(k, v) + assert(k > 0 and k <= #self, "outrange of vector") + + local cnt = #self + for i = cnt, k, -1 do + rawset(self, i+1, self[i]) + end + + rawset(self, k, v) + end + + ---值的索引 + ---@return -1不存在 + function t:indexOf(i_v) + assert(type(self) == 'table') + + local ret = -1 + local cnt = #self + for i = 1, #self do + if self[i] == i_v then + ret = i + end + end + + return ret + end + + ---是否存在某元素 + function t:contains(v) + assert(type(self) == 'table') + return self:indexOf(v) ~= -1 + end + + ---根据下标索引移除元素(低效) + function t:removeAt(idx) + assert(idx <= #self) + table.remove(self, idx) + end + + ---删除值(非贪婪) + ---@return 删除位置 -1未删除 + function t:remove(v) + local ret = self:indexOf(v) + if ret ~= -1 then + self:removeAt(ret) + end + + return ret + end + + ---删除所有值 + function t:removeAll(v) + assert(type(self) == 'table') + error(">>Dee: wait ...") + end + + ---排序 + function t:sort(comparer) + assert(type(self) == 'table') + table.sort(self, comparer) + end + + ---匹配 + ---@param 匹配函数 + ---@return idx,value + function t:find(matcher) + assert(type(self) == 'table') + + local _idx, _value = -1, nil + local cnt = #self + for i = 1, cnt do + if matcher(i, self[i]) then + _value = self[i] + _idx = i + break + end + end + + return _idx, _value + end + + --------------------------------metatable--------------------------------------- + t.__newindex = function(i_t,k,v) + error(">> Dee: [], replace with add()") + end + + t.__tostring = function(i_t) + return table.concat(i_t, ',') + end + + t.__pairs = function(...) + error(">> Dee: Limited access") + end + + setmetatable(t, t) + ----------------------------------------------------------------------- + + return t +end + +return vector
\ No newline at end of file |