Skip to content

Commit

Permalink
More 'precision' issue fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
alexbykoff committed Jun 15, 2016
1 parent 84d1221 commit 00fc750
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
18 changes: 10 additions & 8 deletions src/array-cop.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,15 @@
*/
if (Array.isArray(arr)) {

if (isNaN(precision)) precision = 2;

var mean = 0,
sum = 0,
num = 0,
mul = 1,
precision = precision || 2, // Default precision value
arr = this.flatten(arr);


if (!arr.length) {
return mean;
}
Expand Down Expand Up @@ -106,17 +108,17 @@
});
mean = (harArray.length / harDenominator);
}
return mean.toFixed(precision);
return precision > 0 ? mean.toFixed(precision) : mean;
}
throw new Error("Not an array!");
},

median: function(arr, precision) {
/* Returns median for numeric values. Flattens an array before proceed.
*
* precision: Number — Optional argument, sets the number of digits after a decimal
* point. If omitted then falls back to 2
*/
*
* precision: Number — Optional argument, sets the number of digits after a decimal
* point. If omitted then falls back to 2
*/

if (Array.isArray(arr)) {

Expand Down Expand Up @@ -151,7 +153,7 @@
// If number of Number items is odd then middle item is the median
return newArr[medianItem]
// Otherwise calculate and average of two items in the middle
} else return ((newArr[medianItem - 1] + newArr[medianItem]) / 2).toFixed(Math.abs(precision));
} else return precision > 0 ? ((newArr[medianItem - 1] + newArr[medianItem]) / 2).toFixed(Math.abs(precision)) : (newArr[medianItem - 1] + newArr[medianItem]) / 2;
}
throw new Error("Not an array!");
},
Expand Down Expand Up @@ -333,7 +335,7 @@
result.push(index);
index = arr.indexOf(element, index + 1);
}
return result.length ? result : -1;
return result.length ? result : -1;
}
throw new Error("Not an array!");

Expand Down
2 changes: 1 addition & 1 deletion test/array-cop.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ describe('median() - return median element of the numeric items in array', funct
});

it('should return median with precision = 0', function() {
assert.equal(arrayCop.median([[100, -50, 3], new String, 3], 0), 3);
assert.deepEqual(arrayCop.median([[100, -50, 3], new String, 3], 0), 3);
});

});

0 comments on commit 00fc750

Please sign in to comment.