3 ms·
Pass data recursively You mean back up the stack via the return statement? or via parameters in the function call?
by edmcnulty101 4y ago
Pass data recursively
You mean back up the stack via the return statement?
or via parameters in the function call?
- lesuorac 4y agoEither. Like I could have a recursive solution that returns the sum of the length of the sub-arrays or I could just pass a mutable object and update the length there. Which way would depend on the exact problem (i.e. Strings would be best collected in a StringBuilder rather than concatenated but `lengthParam` would probably more clear if it returned a number instead of using the Array). ``` const lengthParam = (a,p) => { if(Array.isArray(a)) { for(let c of a) { lengthParam(c,p) } } else { p[0] = p[0] + 1 } }; var b = [0] lengthP([1,2,3,[4,5],[6]], b); console.log(b[0]) // 6 ```
- kyberias 4y agoSeems like you want to get the count of "leaves" in a tree expressed as array of arrays. ``` const lengthParam = (a) => { let count = 0; for(let c of a) { if(Array.isArray(c)) { count += lengthParam(c) } else { count++; } } return count; }; ``` Am I hired?