Explained Solution in JavaScript and TypeScript | Daily Problem of JavaScript 30 days |
Intuition\nTransform array according to given function.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1) Edge case: if arr.length
# Intuition\nTransform array according to given function.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1) Edge case: if `arr.length == 0` then return `init`.\n2) The first `val` will be passed in the function as `init`, after 1st iteration `init` will be replaced by `val`.\n```\nif(n > 1){\n    val = fn(init, nums[0]);\n        for(var i = 1; i < n; i++){\n            val = fn(val, nums[i]);\n        }\n    }\n```\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n---\n> I am in initial stage of learning javascript. If you have any suggestion to improve myself please suggest.\n---\n\n# Code\n``` JavaScript []\nvar reduce = function(nums, fn, init) {\n    var n = nums.length, val = 0;\n    if(n == 0){\n        return init;\n    }\n    if(n == 1){\n        val = fn(init, nums[0]);\n        return val;\n    }\n    if(n > 1){\n        val = fn(init, nums[0]);\n        for(var i = 1; i < n; i++){\n            val = fn(val, nums[i]);\n        }\n    }\n    return val;\n};\n```\n``` TypeScript []\ntype Fn = (accum: number, curr: number) => number\n\nfunction reduce(nums: number[], fn: Fn, init: number): number {\n    var n = nums.length, val = 0;\n    if(n == 0){\n        return init;\n    }\n    if(n == 1){\n        val = fn(init, nums[0]);\n        return val;\n    }\n    if(n > 1){\n        val = fn(init, nums[0]);\n        for(var i = 1; i < n; i++){\n            val = fn(val, nums[i]);\n        }\n    }\n    return val;\n};\n```
['TypeScript', 'JavaScript']