Skip to content

Commit

Permalink
Merge pull request #230 from fawcilize/master
Browse files Browse the repository at this point in the history
Adding a sum function to add variable-length arrays
  • Loading branch information
silentmatt authored Jul 23, 2020
2 parents 4327f05 + cfb2b90 commit b5e3d61
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -342,3 +342,13 @@ export function log1p(x) {
export function log2(x) {
return Math.log(x) / Math.LN2;
}

export function sum(array) {
if (!Array.isArray(array)) {
throw new Error('Sum argument is not an array');
}

return array.reduce(function (total, value) {
return total + Number(value);
}, 0);
}
6 changes: 4 additions & 2 deletions src/parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ import {
cbrt,
expm1,
log1p,
log2
log2,
sum
} from './functions';

export function Parser(options) {
Expand Down Expand Up @@ -130,7 +131,8 @@ export function Parser(options) {
fold: arrayFold,
filter: arrayFilter,
indexOf: stringOrArrayIndexOf,
join: arrayJoin
join: arrayJoin,
sum: sum
};

this.consts = {
Expand Down
22 changes: 22 additions & 0 deletions test/functions.js
Original file line number Diff line number Diff line change
Expand Up @@ -463,4 +463,26 @@ describe('Functions', function () {
assert.strictEqual(parser.evaluate('join("", [1, 2, 3])'), '123');
});
});

describe('sum(array)', function () {
it('should fail if the argument is not an array', function () {
var parser = new Parser();
assert.throws(function () { parser.evaluate('sum(1)'); }, /not an array/);
});

it('should return zero with an empty array', function () {
var parser = new Parser();
assert.strictEqual(parser.evaluate('sum([])'), 0);
});

it('should work on a single-element array', function () {
var parser = new Parser();
assert.strictEqual(parser.evaluate('sum([1])'), 1);
});

it('should work on a multi-element array', function () {
var parser = new Parser();
assert.strictEqual(parser.evaluate('sum([1, 2])'), 3);
});
});
});

0 comments on commit b5e3d61

Please sign in to comment.