chunk

function chunk( arr, size ) --> chunks

Description

Creates an array table of elements split into groups the length of size. If arr can’t be split evenly, the final chunk will be the remaining elements.

Parameters

arr

The array table that should be split into chunks.

size

The maximum size of the sub-arrays.

Return Values

chunks

A array table with the chunks.

Code

--ZFUNC-chunk-v1
local function chunk( arr, size )
   local chunks = {}

   local full_packs = math.floor( #arr / size )
   for i = 1, full_packs do
      local sub = {}
      local b = ( i * size ) - ( size - 1 )
      local e = i * size
      for idx = b, e do
         table.insert( sub, arr[ idx ] )
      end
      table.insert( chunks, sub )
   end

   return chunks
end

return chunk

Examples

local t = require( "tapered" )
local chunk = require( "chunk" )

local res = chunk( { "a", "b", "c", "d", "e", "f" }, 3 )

t.is( 2, #res )
t.same( { "a", "b", "c" }, res[ 1 ] )
t.same( { "d", "e", "f" }, res[ 2 ] )

t.done()

Inspired by