Skip to content
This repository

Array.sum returns NaN if a array item is undefined. #1114

Closed
mientjan opened this Issue · 2 comments

3 participants

Mient-jan Stelling Arian Stolwijk Sergio Crisostomo
Mient-jan Stelling

Array.sum returns NaN if a array item is undefined. this issue is found MooTools More 1.4.0.1

the solution is to check if a item is available.

Array.prototype.sum = function(){
    var r = 0;
    for( var i = 0, l = this.length; i < l; ++i ){
        if(this[i]){ r += this[i]; }
    }
    return r;
}
Arian Stolwijk
Owner
arian commented

agreed, or just use .forEach, which already skips undefined values: https://github.com/mootools/mootools-core/blob/master/Source/Core/Core.js#L317-321

Mient-jan Stelling

Yea, that is even better. The code i provided would not work with negative values any way.

here is the fix for both ways to do it.

// i prefer this way because no new function has to be created. 
Array.prototype.sum = function(){
    var r = 0;
    for( var i = 0, l = this.length; i < l; ++i ){
        if( i in this ){ r += this[i]; }
    }
    return r;
}

Array.prototype.sum = function(){
    var r = 0;
    this.forEach(function(n){ r += n; });
    return r;
}
Sergio Crisostomo SergioCrisostomo referenced this issue from a commit in SergioCrisostomo/mootools-more
Sergio Crisostomo SergioCrisostomo Make Array.sum() tolerate undefined elements
Array.sum returns `NaN` if a array item is undefined.

[10, 20, undefined, 30].sum(); // "NaN"

This PR makes:
-  `Array.sum()` ignore `undefined` values
- more explicit in the docs that the method will return NaN if a
*non-number* is present in the array
- adds extra specs

##### PS: - All this is @timwienk 's credit & work!

fixes  #1114
8732880
Sergio Crisostomo SergioCrisostomo referenced this issue from a commit
Sergio Crisostomo SergioCrisostomo Merge: make Array.sum() ignore undefined values
Array.sum returns `NaN` if a array item is undefined.

    [10, 20, undefined, 30].sum(); // "NaN"

This PR makes:
-  `Array.sum()` ignore `undefined` values
- more explicit in the docs that the method will return NaN if a
*non-number* is present in the array
- adds extra specs

fixes  #1114
closes #1258
93cdae0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.