😎 Super duper easy Reduce Method | Javascript | Typescript | Brownie Tip
Intuition\n Describe your first thoughts on how to solve this problem. \nThe objective of this problem is to write a function that performs a reduction transfor
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe objective of this problem is to write a function that performs a reduction transformation based on the output of a callback function with arguments `accumulator` and `current value`. The value obtained by calling fn must be taken `accumulator` for next function call.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis probelm is require to create our `Custom Reduce` function but not in `Array.prototype`.\n\nTo achieve this, we can create a variable named `accumulator` which will assign with initial value and start looping over each element in the `nums` array. For each element, we call the fn function with `accumulator` and value as arguments, and reassign accumulator with returned value. At last return the accumulator.\n\nBy using this approach, we can reduce out the input array efficiently and elegantly.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n``` javascript []\n/**\n * @param {number[]} nums\n * @param {Function} fn\n * @param {number} init\n * @return {number}\n */\nvar reduce = function(nums, fn, init) {\n    let accumulator = init;\n    nums.forEach(num => {\n        accumulator = fn(accumulator, num)\n    })\n\n    return accumulator\n};\n```\n``` typescript []\ntype Fn = (accum: number, curr: number) => number\n\nfunction reduce(nums: number[], fn: Fn, init: number): number {\n    let accumulator = init;\n    nums.forEach(num => {\n        accumulator = fn(accumulator, num)\n    })\n\n    return accumulator\n};\n```\n\n# Brownie Learning :\nIf you understand the above function then to make it run similar to JS reduce HOC method. We just need to change 3 things.\n1. remove the first `nums` argument from function defination.\n2. create a variable name `nums` and assign it with keyword `this`. Why ? because keyword `this` will hold the array on which our custom reduce method called.\n3. assign reduce method to `Array.prototype[CUSTOME_REDUCE_METHOD_NAME] = reduce`\n\nHurray! We have our own custom reduce method similar to JS reduce method.\n\n``` javascript\nArray.prototype.myReduce = function(fn, init) {\n    let nums = this\n    let accumulator = init;\n    nums.forEach(num => {\n        accumulator = fn(accumulator, num)\n    })\n\n    return accumulator\n};\n```
['Array', 'TypeScript', 'JavaScript']