leetcodedaybyday - Beats 83.97% with JavaScript - 90.39% with TypeScript
IntuitionThe problem requires implementing a reduce function that iterates through an array, applies a given function to accumulate values, and returns the fina
# **Intuition**
The problem requires implementing a `reduce` function that iterates through an array, applies a given function to accumulate values, and returns the final result. This is similar to the built-in `Array.prototype.reduce()` method in JavaScript.

# **Approach**
1. **Initialize** `res` with `init` (the starting value).
2. **Iterate** through each element in `nums`:
   - Apply the function `fn(res, num)`, where `res` is the accumulated value and `num` is the current element.
   - Update `res` with the returned value.
3. **Return `res`** after processing all elements.

# **Complexity**
- **Time Complexity:** \(O(n)\)  
  - We iterate through the entire array once.
- **Space Complexity:** \(O(1)\)  
  - We only use a single variable `res` for accumulation.

---

# Code
```javascript []
/**
 * @param {number[]} nums
 * @param {Function} fn
 * @param {number} init
 * @return {number}
 */
var reduce = function(nums, fn, init) {
    let res = init;
    for (let i = 0; i < nums.length; i++){
        res = fn(res, nums[i])
    }
    return res;
};


```

```typescript []
type Fn = (accum: number, curr: number) => number

function reduce(nums: number[], fn: Fn, init: number): number {
    let res = init;
    for (let i = 0; i < nums.length; i++){
        res = fn(res, nums[i]);
    }
    return res;
};


```


['TypeScript', 'JavaScript']