Permalink
Browse files

add basic object support

  • Loading branch information...
1 parent 53458d5 commit e77c5bf472133e0e7c3bec539c096a2f08210a83 @tj tj committed Nov 21, 2012
Showing with 21 additions and 3 deletions.
  1. +9 −3 index.js
  2. +12 −0 test/index.js
View
@@ -8,7 +8,7 @@ var toFunction = require('to-function');
/**
* Sum the given `arr` with callback `fn(val, i)`.
*
- * @param {Array} arr
+ * @param {Array|Object} arr
* @param {Function} fn
* @return {Number}
* @api public
@@ -18,8 +18,14 @@ module.exports = function(arr, fn){
var sum = 0;
if (fn) {
fn = toFunction(fn);
- for (var i = 0; i < arr.length; ++i) {
- sum += fn(arr[i], i);
+ if (Array.isArray(arr)) {
+ for (var i = 0; i < arr.length; ++i) {
+ sum += fn(arr[i], i);
+ }
+ } else {
+ for (var key in arr) {
+ sum += fn(arr[key], key);
+ }
}
} else {
for (var i = 0; i < arr.length; ++i) {
View
@@ -26,4 +26,16 @@ describe('sum(arr)', function(){
return user.age;
}).should.equal(11);
})
+})
+
+describe('sum(obj, fn)', function(){
+ it('should sum values', function(){
+ sum({
+ foo: 1,
+ bar: 2,
+ baz: 3
+ }, function(val){
+ return val;
+ }).should.equal(6);
+ })
})

0 comments on commit e77c5bf

Please sign in to comment.