Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions component.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@
"name": "sum",
"repo": "component/sum",
"description": "Array sum utility",
"version": "0.1.1",
"keywords": ["array", "sum", "utility"],
"version": "0.2.0",
"keywords": [
"array",
"sum",
"utility"
],
"dependencies": {
"component/to-function": "*"
"component/to-function": "1.2.0"
},
"development": {},
"scripts": [
Expand Down
21 changes: 15 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,29 @@ var toFunction = require('to-function');

module.exports = function(arr, fn){
var sum = 0;
var len = arr.length
if (fn) {
fn = toFunction(fn);
if (Array.isArray(arr)) {
for (var i = 0; i < arr.length; ++i) {
sum += fn(arr[i], i);
if (typeof fn != 'function') fn = toFunction(fn);
// array
if (len === +len) {
for (var key = 0; key < len; ++key) {
sum += fn(arr[key], key);
}
} else {
for (var key in arr) {
sum += fn(arr[key], key);
}
}
} else {
for (var i = 0; i < arr.length; ++i) {
sum += arr[i];
// array
if (len === +len) {
for (var key = 0; key < len; ++key) {
sum += arr[key]
}
} else {
for (var key in arr) {
sum += arr[key]
}
}
}
return sum;
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"name": "sum-component",
"version": "0.1.1",
"version": "0.2.0",
"description": "Sum utility",
"dependencies": {
"to-function": "*"
"to-function": "~1.2.0"
},
"devDependencies": {
"mocha": "*",
Expand Down
17 changes: 16 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,25 @@ describe('sum(arr)', function(){
return user.age;
}).should.equal(11);
})

it('should sum array like objects', function(){
sum({0:1,1:2,2:3,length:3}).should.equal(6);
sum({0:1,1:2,2:3,length:3}, function(item){
return item
}).should.equal(6);
})
})

describe('sum(obj, fn)', function(){
describe('sum(obj)', function(){
it('should sum values', function(){
sum({
foo: 1,
bar: 2,
baz: 3
}).should.equal(6);
})

it('should support callbacks', function(){
sum({
foo: 1,
bar: 2,
Expand Down