Q:

Recurring a function splicing values into an array until condition met

This function finds a gap larger than a value, fills it with the average of the neighbouring values and returns the new array. 
I need to recur this function until there is no more gaps greater than the gap value, in the example 5. 
How do I recur this function until there are no more gaps? 

var chain = [0,2,6,44,70]
function fillgaps(chain,gap){
 var len = chain.length
 for(i=1;i<len;i++){
  var g = chain[i]-chain[i-1] 
   if(g>gap){
    var avrg = (chain[i]+chain[i-1])/2
    chain.splice(i,0,avrg)
    var len = 0
   }
 }
 return chain
}
var test = fillgaps(chain,5)
console.log(chain)

A:

You don't have to call the whole function again.  Instead place the index back a bit and let it continue from there, so it will reassess the new interval that was introduced:

function fillgaps(chain,gap){
    var len = chain.length
    for(i=1;i<len;i++){
        var g = chain[i]-chain[i-1] 
        if(g>gap){
            var avrg = (chain[i]+chain[i-1])/2;
            chain.splice(i,0,avrg);
            len++;
            i--;
        }
    }
    return chain;
}
var chain = [0,2,6,44,70];
var test = fillgaps(chain,5)
console.log(test)

