Search code examples
javascriptecmascript-6typed-arrays

sum of uint8array javascript


I'm trying to sum and then average a stream of data, some code here.

var getAverage = function(dataArray){
        var total,
        sample = dataArray.length,
        eArray = Array.prototype.slice.call(dataArray);
        for (var i = 0; i< sample; i++) {
          total+= eArray[i];
        }
        return total;
    }
    var output = function(){
        //source data
        var dataArray = new Uint8Array(bufferLength);
        analyser.getByteTimeDomainData(dataArray);
        var average = getAverage(dataArray);
        $('#average').text(average);
        window.requestAnimationFrame(output);

Every element in the array returns a number, but it still returns NaN. Help?


Solution

  • The declared variable total is undefined which means it will create NaN (Not-a-Number) when a number is added to it.

    Also, Typed Array (ArrayBuffer/views) and Array are not the same, and converting a typed array to an ordinary Array is making iteration slower as typed arrays are actual byte-buffers while Arrays are (node) lists. That on top of the cost of conversion itself.

    Just add them straight forward. Remember to divide the sum on length and of course to initialize total:

    var getAverage = function(dataArray){
        var total = 0,                               // initialize to 0
            i = 0, length = dataArray.length;
        while(i < length) total += dataArray[i++];   // add all
        return length ? total / length : 0;          // divide (when length !== 0)
    }