Skip to content

Array.reduce should accept undefined as an initial value #727

@Validark

Description

@Validark
console.log([].reduce(() => {}, undefined)); // should be undefined

TypescriptToLua Playground

TS Playground

This is the more correct code roblox-ts uses:

function TS.array_reduce(list, callback, ...)
	local first = 1
	local last = #list
	local accumulator
	-- support `nil` initialValues
	if select("#", ...) == 0 then
		if last == 0 then
			error("Reduce of empty array with no initial value at Array.reduce", 2)
		end
		accumulator = list[first]
		first = first + 1
	else
		accumulator = ...
	end
	for i = first, last do
		accumulator = callback(accumulator, list[i], i - 1, list)
	end
	return accumulator
end

function TS.array_reduceRight(list, callback, ...)
	local first = #list
	local last = 1
	local accumulator
	-- support `nil` initialValues
	if select("#", ...) == 0 then
		if first == 0 then
			error("Reduce of empty array with no initial value at Array.reduceRight", 2)
		end
		accumulator = list[first]
		first = first - 1
	else
		accumulator = ...
	end
	for i = first, last, -1 do
		accumulator = callback(accumulator, list[i], i - 1, list)
	end
	return accumulator
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions