javascriptrecursionclosurespure-function

Use closure to purify a function which builds an object through recursion — JavaScript


I've made a promise based function which crawls up a hierarchy until it reaches the top, and resolves with an object containing the structure. My only gripe with the code is that I modify variables outside the function body, meaning that it is not a pure function. I've looked into JavaScript closures, and I fully grasp trivial uses of them. But I'm struggling to figure out how/if they can help make my function pure. My attempts at making a closure so far have only overwritten the variables, not modified them. Here is the code in question using global variables:

/* I want to move these variables inside function body to purify 'getPriorRows'*/
let priorRows = {}, level = 0;

const getPriorRows = id => new Promise(resolve => {
  fetch(`/api/org/${id}`).then(result => {

    /* global varaiables are modified here */
    priorRows[level++] = result;

    if (result.parentID) resolve(getPriorRows(result.parentID));
    else resolve(priorRows);

  });
});

getPriorRows('123432').then(result => console.log(result));

Any input on the matter is greatly appreciated.


Solution

  • Pass the values as arguments:

    function getPriorRows(id, priorRows = {}, level = 0) {
      return fetch(`/api/org/${id}`).then(result => {
        /* global varaiables are modified here */
        priorRows[level] = result;
    
        if (result.parentID) return getPriorRows(result.parentID, priorRows, level+1);
        else return priorRows;
      });
    }
    
    getPriorRows('123432').then(result => console.log(result));
    

    You can use either default parameters or a wrapper function, you don't even need a closure:

    function getAll(id) { return getPriorRows(id, {}, 0); }
    

    Also the I removed the Promise constructor antipattern.