Nodejs Array Sum sum()

Here you can find the source of sum()

Method Source Code

const assert = require('assert')

Array.prototype.sum = function() {
   return this.reduce((sum, el) => sum + el, 0)
}

assert.equal([].sum(), 0)//from ww  w  . j  a va2  s . c  o m
assert.equal([2, 5, 7].sum(), 14)

Related

  1. sum()
    Array.prototype.sum = function() {
      return this.reduce(function(prev, curr) {
        return prev + curr;
      });
    };
    module.exports = Array.prototype.sum;
    
  2. sum()
    Array.prototype.sum  = function() {
        var res = 0;
        for(var p in this)
      res += this[p];
        return res;
    };
    var a = [1, 2, 3];
    console.log(0 in a);
    
  3. sum()
    Array.prototype.sum = function() {
        var res = 0;
        for(var i=0;i<this.length;++i)
      res += this[i];
        return res;
    };
    var s = [1, 2, 3].sum();
    
  4. sum()
    Array.prototype.sum = function () {
      var sum = 0;
      for (var i = 0; i < this.length; i++) {
        sum += this[i];
      };
      return sum;
    console.log([1, 3, 12, 33, 2].sum());
    
  5. sum()
    Array.prototype.sum = function () {
        var length = this.length;
        var total = 0;
        for (var i = 0; i < length; i++) {
           total += this[i];
        return total;
    };
    
  6. sum()
    Array.prototype.sum = function() {
        var res = 0;
        for(var p in this)
      res += this[p];
        return res;
    };
    var a = [1, 2, 3];
    var all_in = true;
    for(var i=0;i<5;++i)
    ...
    
  7. sum()
    var ary1 = new Array(12, 55, 43, 32, 44);
    var ary2 = new Array(12, 33, 1);
    Array.prototype.sum = function() {
        var output = 0;
        for (var i = 0; i < this.length; i++) {
            output += this[i];
        return output;
    };
    ...
    
  8. sum()
    Array.prototype.sum = function(){
      for(var i=0,sum=0;i<this.length;sum+=this[i++]);
      return sum;
    
  9. sum()
    var numbers = [1,2,3,4,5,6];
    Array.prototype.sum = function(){
      return this.reduce(function(p, c){
        return p+c;
      })
    var result = numbers.sum();
    console.log(result);
    console.log(numbers);
    ...