Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions lua/spec/array_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,54 @@ describe('array', function()
end)
end)

describe('createRepeatedArray', function()
it('check', function()
assert.are_same({1}, Array.rep(1, 1))
assert.are_same({2, 2}, Array.rep(2, 2))
assert.are_same({3, 3, 3}, Array.rep(3, 3))
assert.are_same(
{
'The quick brown fox jumps over the lazy dog',
'The quick brown fox jumps over the lazy dog',
'The quick brown fox jumps over the lazy dog',
'The quick brown fox jumps over the lazy dog',
'The quick brown fox jumps over the lazy dog'
},
Array.rep('The quick brown fox jumps over the lazy dog', 5)
)
assert.are_same(
{
{1, 2, 3},
{1, 2, 3},
},
Array.rep(Array.range(1, 3), 2)
)
assert.are_same(
{
{1, 2, 3},
{1, 2, 3},
},
Array.rep(Array.range(1, 3), 2, Array.copy)
)
end)

it('check count==0', function ()
assert.is_true(Array.equals({}, Array.rep('Lorem ipsum', 0)))
end)

it('Error if illegal arguments are passed in', function()
assert.error(function ()
return Array.rep(nil, 1)
end)
assert.error(function ()
return Array.rep('nil', -3)
end)
assert.error(function ()
return Array.rep(nil, 1)
end)
end)
end)

describe('Sub', function()
it('check', function()
local a = {3, 5, 7, 11}
Expand Down
30 changes: 30 additions & 0 deletions lua/wikis/commons/Array.lua
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,36 @@ function Array.copy(tbl)
return copy
end

---Creates an array that contains `count` copies of the specified element.
---
---If `count == 0`, then an empty array is returned.
---
---If `element` is a table and `copyFunction` is not specified,
---then all elements in the returned array are reference equal.
---@generic T
---@param element T
---@param count integer
---@param copyFunction? fun(origElement: T): T
---@return T[]
---@nodiscard
function Array.rep(element, count, copyFunction)
assert(element ~= nil, 'element must not be nil')
if count < 0 then
error('count must be non-negative')
elseif count == 0 then
return {}
end
local arr = {}
for _ = 1, count do
if copyFunction then
table.insert(arr, copyFunction(element))
else
table.insert(arr, element)
end
end
return arr
end

---Returns true if two arrays are equal to each other.
---@param arr1 any[]
---@param arr2 any[]
Expand Down
Loading