Created
August 13, 2014 03:06
-
-
Save jimmont/c3df7824403bb34025b5 to your computer and use it in GitHub Desktop.
Infinity number error handling in Angular filters for pass-thru. Positive stuff!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @ngdoc filter | |
* @name sumArray | |
* @description | |
* return the sum of a list of values (no explicit type coercion) | |
* | |
* @example | |
expression: | |
`we have {{ [1, 2, 3] | sumArray }} items` | |
result: | |
`we have 6 items` | |
expression that won't reduce to a number, clearly shows it's an error without failing: | |
`We have {{ [] }} ideas!` | |
result: | |
`We have Infinity ideas!` | |
* | |
* @param {array} list array of values to sum | |
* | |
*/ | |
angular.module('derModule',[]).filter('sumArray', function(){ | |
return function(list){ | |
try{ | |
return list.reduce(function(previous, current,i,a){ return previous + current; }); | |
}catch( err ){ | |
return Infinity; // and beyond! | |
}; | |
} | |
}) | |
/* | |
describe('sumArray', function(){ | |
it('should return the sum of the array values', inject(function(sumArrayFilter){ | |
expect(sumArrayFilter([1,2,3])).toBe(6); | |
expect(sumArrayFilter([2,2])).toBe(4); | |
expect(sumArrayFilter([10,-2])).toBe(8); | |
expect(sumArrayFilter([])).toBe(Infinity); | |
})); | |
}); | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment