-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray Reduce Transformation.js
More file actions
57 lines (40 loc) · 1.02 KB
/
Array Reduce Transformation.js
File metadata and controls
57 lines (40 loc) · 1.02 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// 2626. Array Reduce Transformation
/**
* @param {number[]} nums
* @param {Function} fn
* @param {number} init
* @return {number}
*/
// Classic for loop
var reduce = function(nums, fn, init) {
let total = init
for(i = 0; i<nums.length; i++){
total = fn(total, nums[i])
}
return total;
};
// for...of with index
// var reduce = function(nums, fn, init) {
// let total = init;
// for (let [i, val] of nums.entries()) {
// total = fn(total, val, i);
// }
// return total;
// };
// forEach
// var reduce = function(nums, fn, init) {
// let total = init;
// nums.forEach((val, i) => {
// total = fn(total, val, i);
// });
// return total;
// };
// recursion
// var reduce = function(nums, fn, init, i = 0) {
// if (i >= nums.length) return init;
// return reduce(nums, fn, fn(init, nums[i], i), i + 1);
// };
// built-in Array.prototype.reduce (meta-solution)
// var reduce = function(nums, fn, init) {
// return nums.reduce((acc, val, i) => fn(acc, val, i), init);
// };