Posts

Showing posts with the label methods

Recursively calculate the sum of an Array of integers in JavaScript

Recursively calculate the sum of an Array of integers in JavaScript I wanted to write a JavaScript program to compute the sum of an array of integers Recursively . Expected Results Input : [1, 2, 3, 4, 5, 6] Output : 21 I achieved the above results with this code: function calculateSum(array) { if (array instanceof Array){ if (!array.some(isNaN)) { var total = 0; array.forEach(function (value) { total += value; }); return total; } return "Provide an Array with only Numeric Values"; } return "Please provide an Array"; } But I'm looking for a solution that uses Recursion . EDIT : I started doing the above exercise to practice Recursion . I was having a hard time figuring that out. So, That's why I posted this. I'd be glad if you understood. Thanks in advance. What have you tried? What specifically do you need help with? ...

How to use class variables?

How to use class variables? A simple question. If I have class A with methods m1 and m2 . Is it a good practice that m1 changes the state of A . And then when m2 is called it relies on A 's state being changed by m1 . In other words if m2 is dependent on m1 being called before m2 being called. With m1 and m2 being both private. Worded differently is it O.K. for private methods to consider the object state as shared memory? Problem arises when they are called out of order. But with the benefit of not having to copy arguments. Any advice? 1 Answer 1 Your description is not a good design. Class variables should have class invariants that are true before and after any (and all) method invocations. The order of calls should not matter. The way you described it make is sounds that there will be cases during which this will not be true, for example if m1 is not called yet and m2 is. Moreover...