diff --git a/lua/spec/array_spec.lua b/lua/spec/array_spec.lua index 696ac06ee4a..8c13be8d5ba 100644 --- a/lua/spec/array_spec.lua +++ b/lua/spec/array_spec.lua @@ -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} diff --git a/lua/wikis/commons/Array.lua b/lua/wikis/commons/Array.lua index 28061222ee2..dad519958fe 100644 --- a/lua/wikis/commons/Array.lua +++ b/lua/wikis/commons/Array.lua @@ -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[]