Skip to content

Commit

Permalink
Add Sum method (#34)
Browse files Browse the repository at this point in the history
  • Loading branch information
Connor Ruggles authored and jreina committed Oct 7, 2018
1 parent 6544d9c commit ce3161c
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,6 @@ typings/

# Serverless directories
.serverless

# vscode settings
.vscode/settings.json
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ interface Array<T> {
TakeWhile<T>(predicate: (X: T) => boolean): Array<T>;
Union<T>(adder: Array<T>): Array<T>;
Where<T>(predicate: (X: T) => boolean): Array<T>;
Sum<number>(): number;
}
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const TakeWhile = require('./src/TakeWhile');
const ToDictionary = require('./src/ToDictionary');
const Union = require('./src/Union');
const Where = require('./src/Where');
const Sum = require('./src/Sum');

const bindAll = function() {
Array.prototype.Aggregate = Aggregate;
Expand All @@ -26,6 +27,7 @@ const bindAll = function() {
Array.prototype.ToDictionary = ToDictionary;
Array.prototype.Union = Union;
Array.prototype.Where = Where;
Array.prototype.Sum = Sum;
};

module.exports = bindAll;
13 changes: 13 additions & 0 deletions src/Sum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* @template number?
* @returns {number}
*/
function Sum() {
let sum = 0;
for (let x of this) {
if (x != null) sum += x;
}
return sum;
}

module.exports = Sum;
21 changes: 21 additions & 0 deletions test/Sum.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const expect = require('chai').expect;
require('..')();

describe('Array#prototype#Sum', () => {
const input = [1, 2, 3];
const input_with_null = [1, 2, null, 3];

it('should display the correct sum', () => {
const expected = input.reduce((prev, x) => x + prev);

const actual = input.Sum();
expect(actual).to.eql(expected);
});

it('should not include null values in sum', () => {
const expected = input_with_null.reduce((prev, x) => x + prev);

const actual = input_with_null.Sum();
expect(actual).to.eql(expected);
});
});

0 comments on commit ce3161c

Please sign in to comment.