Nodejs Array Sum sum()

Here you can find the source of sum()

Method Source Code

// The JavaScript standard now includes functional additions to array like map,
// filter and reduce, but sadly is missing the convenience functions range and sum.
// Implement a version of range and sum (which you can then copy and use in your future Kata to make them smaller).

// Array.range(start, count) should return an array containing count numbers
// from start to start +
// count Example: Array.range(0, 3) returns [0, 1, 2]

// Array.sum() return the sum of all numbers in the array Example: [0, 1, 2].sum() returns 3
// Example: Array.range(-1,4).sum() should return 2

// While not forbidden try to write both function without using a for loop

var val = [1, 2, 3];

function array(val){
  this.val = val;/*  ww  w. jav a  2  s.c o  m*/
}

Array.prototype.sum = function(){
  return this.reduce(function(a, b){
    return a + b;
  });
};

console.log(val.sum());

Array.range = function(start, count){
  var arr = [],
  val = start;
  while(count > 0) {
    arr.push(val);
    count--;
    val++;
  }
  return arr;
};

console.log(Array.range(0,3));

Related

  1. sum()
    Array.prototype.sum = function() {
      var sum = 0;
      this.forEach(function(k) {
        sum += k;
      });
      return sum;
    };
    
  2. sum()
    Array.prototype.sum = function()
      if (this.length < 1) {
        return Number.NaN;
      var sum = 0;
      this.forEach(function(a) {
        sum += a;
      });
    ...
    
  3. sum()
    Array.prototype.sum = function () {
        return this.reduce(function(previousValue, currentValue) {
            return previousValue + currentValue;
        });
    };
    
  4. sum()
    Array.range = function(start, count) {
      var newArray = [];
      for( var i = 0, j = start; i< count; i++, j++)
        newArray.push(j);
      return newArray;
    Array.prototype.sum = function () {
        var sum = 0;
        this.forEach(function (value) {
    ...
    
  5. sum()
    Array.prototype.sum = function () {
      var t = 0;
      for (var i = 0; i < this.length; i++ ) {
        t += this[i];
      return t;
    
  6. sum()
    Array.prototype.sum = function(){
      var ret = this[0];
      for(var i=1;i<this.length;i++){
        ret += this[i]
      return ret;
    
  7. sum()
    Array.prototype.sum = function () {
        var result = 0;
        for (var i = 0; i < this.length; i++) {
            result += this[i];
        return result;
    };
    
  8. sum()
    Array.prototype.sum = function() {
      var result = 0;
      this.forEach(function(item){
        result += item;
      });
      return result;
    console.log([1,2,3,4,5,6,7,8,9,10].sum());
    function Person(name, age) {
    ...
    
  9. sum()
    Array.prototype.sum = function() {
      var sum = 0;
      for (var i = 0; i < this.length; i++) {
        sum += this[i];
      return sum;
    };