Pumunta sa nilalaman

Module:table/extendIfNot

Mula Wiksiyonaryo


local table_insert_if_not_module = "Module:table/insertIfNot"
local table_shallow_copy_module = "Module:table/shallowCopy"

local require = require
local type = type

local function insert_if_not(...)
	insert_if_not = require(table_insert_if_not_module)
	return insert_if_not(...)
end

local function shallow_copy(...)
	shallow_copy = require(table_shallow_copy_module)
	return shallow_copy(...)
end

local function extend_with_pos(list, new_items, options)
	local i = 1
	while true do
		local item = new_items[i]
		if item == nil then
			return list
		end
		local success = insert_if_not(list, item, options)
		if success then
			options.pos = options.pos + 1
		end
		i = i + 1
	end
end

local function extend_with_options_as_pos(list, new_items, pos)
	local i = 1
	while true do
		local item = new_items[i]
		if item == nil then
			return list
		end
		local success = insert_if_not(list, item, pos)
		if success then
			pos = pos + 1
		end
		i = i + 1
	end
end

local function extend_without_pos(list, new_items, options)
	local i = 1
	while true do
		local item = new_items[i]
		if item == nil then
			return list
		end
		insert_if_not(list, item, options)
		i = i + 1
	end
end

--[==[
Extend an existing list by a new list, using {insertIfNot()} for each item.

`options` is an optional table of additional options to control the behavior of the operation. The following options are recognized:
* `pos`: As in {insertIfNot()}.
* `comparison`: As in {insertIfNot()}.
* `key`: As in {insertIfNot()}.
* `combine`: As in {insertIfNot()}.

Unlike {insertIfNot()}, this function does not return a boolean indicating whether any items were inserted.]==]
return function(list, new_items, options)
	if options == nil then
		return extend_without_pos(list, new_items)
	elseif type(options) == "number" then
		return extend_with_options_as_pos(list, new_items, options)
	end
	local pos = options.pos
	if pos == nil then
		return extend_without_pos(list, new_items, options)
	end
	return extend_with_pos(list, new_items, shallow_copy(options))
end