-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcollection.lua
85 lines (66 loc) · 2.06 KB
/
collection.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
Collection = {}
Collection.__index = Collection
setmetatable(Collection, {
__call = function (cls, ...)
return cls.new(...)
end,
})
function Collection.new(parentTable)
parentTable = parentTable or (parentTable == nil and {})
local self = setmetatable({}, Collection)
self._valuesArray = parentTable
function self:push(value)
table.insert(self._valuesArray, value)
return self
end
function self:pop()
table.remove(self._valuesArray)
return self
end
function self:merge(...)
local mainTable = self._valuesArray
for _,table2 in ipairs({...}) do
for key,value in pairs(table2) do
if (type(key) == "number") then
table.insert(mainTable,value)
else
mainTable[key] = value
end
end
end
return self
end
function self:where(columnName, columnValue)
local returnArray = {}
for key, object in ipairs(self._valuesArray) do
if (object[columnName] == columnValue) then
table.insert(returnArray, object)
end
end
return Collection(returnArray)
end
function self:count()
return #self._valuesArray
end
function self:at(index)
return self._valuesArray[index]
end
function self:forEach(callbackFunction)
for key, collectionElement in ipairs(self._valuesArray) do
callbackFunction(collectionElement, key)
end
end
function self:chunk(chunkIndex)
local chunkedCollection = Collection()
local secondaryCollection = Collection()
self:forEach(function(collectionItem, index)
secondaryCollection:push(collectionItem)
if index % chunkIndex == 0 or index == self:count() then
chunkedCollection:push(secondaryCollection)
secondaryCollection = Collection()
end
end)
return chunkedCollection
end
return self
end