Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.14 KB | None | 0 0
  1. Collection = {}
  2. Collection.__index = Collection
  3.  
  4. setmetatable(Collection, {
  5.   __call = function (cls, ...)
  6.     return cls.new(...)
  7.   end,
  8. })
  9.  
  10. function Collection.new(parentTable)
  11.     parentTable = parentTable or (parentTable == nil and {})
  12.  
  13.     local self = setmetatable({}, Collection)
  14.     self._valuesArray = parentTable
  15.  
  16.     function self:push(value)
  17.         table.insert(self._valuesArray, value)
  18.         return self
  19.     end
  20.  
  21.     function self:pop()
  22.         table.remove(self._valuesArray)
  23.         return self
  24.     end
  25.  
  26.     function self:merge(...)
  27.         local mainTable = self._valuesArray
  28.            
  29.         for _,table2 in ipairs({...}) do
  30.             for key,value in pairs(table2) do
  31.                 if (type(key) == "number") then
  32.                     table.insert(mainTable,value)
  33.                 else
  34.                     mainTable[key] = value
  35.                 end
  36.             end
  37.         end
  38.  
  39.         return self
  40.     end
  41.  
  42.     function self:where(columnName, columnValue)
  43.         local returnArray = {}
  44.  
  45.         for key, object in ipairs(self._valuesArray) do
  46.             if (object[columnName] == columnValue) then
  47.                 table.insert(returnArray, object)
  48.             end
  49.         end
  50.  
  51.         return Collection(returnArray)
  52.     end
  53.  
  54.     function self:count()
  55.         return #self._valuesArray
  56.     end
  57.  
  58.     function self:at(index)
  59.         return self._valuesArray[index]
  60.     end
  61.  
  62.     function self:forEach(callbackFunction)
  63.         for key, collectionElement in ipairs(self._valuesArray) do
  64.             callbackFunction(collectionElement, key)
  65.         end
  66.     end
  67.  
  68.     function self:chunk(chunkIndex)
  69.         local chunkedCollection = Collection()
  70.         local secondaryCollection = Collection()
  71.  
  72.         self:forEach(function(collectionItem, index)
  73.             secondaryCollection:push(collectionItem)
  74.        
  75.             if index % chunkIndex == 0 or index == self:count() then
  76.                 chunkedCollection:push(secondaryCollection)
  77.                 secondaryCollection = Collection()
  78.             end
  79.         end)
  80.  
  81.         return chunkedCollection
  82.     end
  83.  
  84.     return self
  85. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement