loading...

Discussion on: What’s your alternative solution? Challenge #11

Collapse
aminnairi profile image
Amin

My take at the challenge using a recursive function, immutability and the incremental average algorithm. Also added a generator function to easily generate a generator of numbers in a given range.

"use strict";

function* range( start, stop ) {

    if ( ! Number.isInteger( start ) ) {

        throw new TypeError( "Expected first argument to be an integer." );

    }

    if ( ! Number.isInteger( stop ) ) {

        throw new TypeError( "Expected second argument to be an integer." );

    }

    for ( let value = start; value <= stop; value++ ) {

        yield value;

    }

}

function average( generator, previousAverage = 0, previousIndex = 0 ) {

    if ( Object.prototype.toString.call( generator ) !== "[object Generator]" ) {

        throw new TypeError( "Expected first argument to be a generator." );

    }

    const { value, done } = generator.next();

    if ( done ) {

        return previousAverage;

    }

    if ( ! Number.isInteger( value ) ) {

        throw new TypeError( "Expected first argument to be a generator of integers." );

    }

    const nextIndex     = previousIndex + 1;
    const nextAverage   = ( value - previousAverage ) / nextIndex;

    return average( generator, previousAverage + nextAverage, nextIndex );

}

console.log( average( range( 1, 3 ) ) ); // 2
console.log( average( range( 1, 5 ) ) ); // 3
console.log( average( range( 1, 6 ) ) ); // 3.5