diff --git a/component.json b/component.json index 8629e43..a21c662 100644 --- a/component.json +++ b/component.json @@ -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": [ diff --git a/index.js b/index.js index cad39e3..91e471e 100644 --- a/index.js +++ b/index.js @@ -16,11 +16,13 @@ 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) { @@ -28,8 +30,15 @@ module.exports = function(arr, fn){ } } } 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; diff --git a/package.json b/package.json index b167640..ec55a1c 100644 --- a/package.json +++ b/package.json @@ -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": "*", diff --git a/test/index.js b/test/index.js index 84e9de9..195d6e8 100644 --- a/test/index.js +++ b/test/index.js @@ -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,