--[[
	Races a set of Promises and returns the first one that resolves,
	cancelling the others.
]]

function Promise.race(promises)
	assert(type(promises) == "table", "Please pass a list of promises to Promise.race")

	for i, promise in ipairs(promises) do
		assert(Promise.is(promise), ("Non-promise value passed into Promise.race at index #%d"):format(i))
	end

	return Promise.new(function(resolve, reject, onCancel)
		local function finalize(callback)
			return function (...)
				for _, promise in ipairs(promises) do
					promise:cancel()
				end

				return callback(...)
			end
		end

		onCancel(finalize(reject))

		for _, promise in ipairs(promises) do
			promise:andThen(finalize(resolve), finalize(reject))
		end
	end)
end
