Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.