Skip to content

Commit b5e3d61

Browse files
authored
Merge pull request #230 from fawcilize/master
Adding a sum function to add variable-length arrays
2 parents 4327f05 + cfb2b90 commit b5e3d61

File tree

3 files changed

+36
-2
lines changed

3 files changed

+36
-2
lines changed

src/functions.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,3 +342,13 @@ export function log1p(x) {
342342
export function log2(x) {
343343
return Math.log(x) / Math.LN2;
344344
}
345+
346+
export function sum(array) {
347+
if (!Array.isArray(array)) {
348+
throw new Error('Sum argument is not an array');
349+
}
350+
351+
return array.reduce(function (total, value) {
352+
return total + Number(value);
353+
}, 0);
354+
}

src/parser.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ import {
4848
cbrt,
4949
expm1,
5050
log1p,
51-
log2
51+
log2,
52+
sum
5253
} from './functions';
5354

5455
export function Parser(options) {
@@ -130,7 +131,8 @@ export function Parser(options) {
130131
fold: arrayFold,
131132
filter: arrayFilter,
132133
indexOf: stringOrArrayIndexOf,
133-
join: arrayJoin
134+
join: arrayJoin,
135+
sum: sum
134136
};
135137

136138
this.consts = {

test/functions.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,4 +463,26 @@ describe('Functions', function () {
463463
assert.strictEqual(parser.evaluate('join("", [1, 2, 3])'), '123');
464464
});
465465
});
466+
467+
describe('sum(array)', function () {
468+
it('should fail if the argument is not an array', function () {
469+
var parser = new Parser();
470+
assert.throws(function () { parser.evaluate('sum(1)'); }, /not an array/);
471+
});
472+
473+
it('should return zero with an empty array', function () {
474+
var parser = new Parser();
475+
assert.strictEqual(parser.evaluate('sum([])'), 0);
476+
});
477+
478+
it('should work on a single-element array', function () {
479+
var parser = new Parser();
480+
assert.strictEqual(parser.evaluate('sum([1])'), 1);
481+
});
482+
483+
it('should work on a multi-element array', function () {
484+
var parser = new Parser();
485+
assert.strictEqual(parser.evaluate('sum([1, 2])'), 3);
486+
});
487+
});
466488
});

0 commit comments

Comments
 (0)