0

I have a recursive function that I would like to hide as an implementation detail. Here is are the two functions that I have to start:

function f(n) {
    return fIter(2,1,0,n);
}
function fIter(a,b,c,n) {
    return n===0 ? c : fIter(a+2*b+3*c, a,b,n-1);
}
console.log(f(5))

What would be the suggested way to hide the implementation details? Two examples that came to mind were:

const f = n => (function fIterative(a, b, c, n) {
    return (n===0) ? c : fIterative(a+2*b+3*c, a, b, n-1)
})(2,1,0,n);
console.log(f(5))

And:

function f(n) {
    function fIter(a,b,c,n) {
        return n===0 ? c : fIter(a+2*b+3*c, a,b,n-1);
    }
    return fIter(2,1,0,n);
}
console.log(f(5))
David542
  • 104,438
  • 178
  • 489
  • 842
  • Not sure what you mean by "hide". From whom? From where? `fIter` already is an implementation detail, if you give me only `f`. – Bergi May 16 '22 at 22:35
  • @bergi -- I suppose hide it from the global scope. – David542 May 16 '22 at 22:37
  • 2
    For that, use a) your last snippet b) the IIFE [module pattern](https://stackoverflow.com/questions/26092101/what-is-this-javascript-pattern-called-and-why-is-it-used) c) ES6 modules – Bergi May 16 '22 at 22:38
  • BTW, your naming is misleading. `fIter()` is recursive, not iterative. – Barmar May 16 '22 at 22:45

0 Answers0