I have a problem to determine the complexity of my algorithm because it use features of ES6 and of course they are chained methods. I already know some of basic complexity of those method for example the complexity of Array.prototype.map is O(n). But when we want to determine a complexity of an algorithm, how do we manage chained method ?
For example, consider we have a function which return for an array the sum of its positive numbers
let sumPositive = arr => arr.filter(i => i > 0).reduce((a, b) => a + b, 0);
console.log(sumPositive([1, 2, 3, -4])); // 6
console.log(sumPositive([1, 2, 3, 4])); // 10
Therefore, what is the complexity of that function ?
Another example is this algorithm which for a given string, return the counts of each character in the string
let charCount = str => str.split('').map(
(c,_,str) => str.filter(i => i===c)
).reduce((a, b) => a.hasOwnProperty(b[0]) ? a : ({...a, [b[0]]: b.length}), {});
console.log(charCount("hi")); // {"h": 1, "i": 1}
console.log(charCount("hello to you")); // {"h": 1, "e": 1, "l": 2, "o": 3, " ": 2, "t": 1, "y": 1, "u": 1}
So for this second I need to know especially its complexity because we are dealing with nested method like the filter which is being call inside a map
So any general method to determine the complexity of such algorithm are welcome.
Note: All the complexity in this question is the time-complexity not space
Thanks
O(n^2), as for each character in the array we must search every other character in the array in the worst case.O(n) + n. Because shouldn'tO(n) * nwill ben^2like 2 * 2 will be 4.