Skip to content

Instantly share code, notes, and snippets.

@jimmont
Created August 13, 2014 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jimmont/c3df7824403bb34025b5 to your computer and use it in GitHub Desktop.
Save jimmont/c3df7824403bb34025b5 to your computer and use it in GitHub Desktop.
Infinity number error handling in Angular filters for pass-thru. Positive stuff!
/**
* @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