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)

2 answers

  • answered 2018-01-11 19:50 trincot

    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)

  • answered 2018-01-11 19:50 Nina Scholz

    You could reduce the array by using the last item of the result array and the actual item and use a function for checking the gap.

    If a gap is found, the array is extended with the average and checked for a gap again.

    function fillgaps(chain, gap) {
        const
            iter = a => a.reduce((r, v) => r && r.concat(fill(r.pop(), v)) || [v], undefined),
            fill = (a, b) => gap + a < b ? iter([a, (a + b) / 2, b]) : [a, b];
    
        return iter(chain);
    }
    
    var chain = [0, 2, 6, 44, 70],
        result = fillgaps(chain, 5);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }