forked from TypeScriptToLua/TypeScriptToLua
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayReduce.ts
More file actions
29 lines (25 loc) · 833 Bytes
/
ArrayReduce.ts
File metadata and controls
29 lines (25 loc) · 833 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// https://www.ecma-international.org/ecma-262/9.0/index.html#sec-array.prototype.reduce
function __TS__ArrayReduce<T>(
this: void,
arr: T[],
callbackFn: (accumulator: T, currentValue: T, index: number, array: T[]) => T,
...initial: Vararg<T>
): T {
const len = arr.length;
let k = 0;
let accumulator = undefined;
// Check if initial value is present in function call
if (select("#", ...initial) !== 0) {
accumulator = select(1, ...initial);
} else if (len > 0) {
accumulator = arr[0];
k = 1;
} else {
// tslint:disable-next-line: no-string-throw
throw "Reduce of empty array with no initial value";
}
for (const i of forRange(k, len - 1)) {
accumulator = callbackFn(accumulator, arr[i], i, arr);
}
return accumulator;
}