--!strict

local function defaultFilter(...: any)
	return true
end

local function onSpawned<U>(parent: Instance, callback: (child: U) -> (), filter: ((child: Instance) -> boolean)?)
	local filterer = (filter or defaultFilter) :: (Instance) -> boolean
	
	for _, child in parent:GetChildren() :: { any } do
		if filterer(child) then
			task.spawn(callback, child)
		end
	end
	
	local signal = parent.ChildAdded:Connect(function(child: any)
		if filterer(child) then
			callback(child)
		end
	end)
	
	return function()
		signal:Disconnect()
	end
end

return onSpawned
