Search code examples
angularjsangularjs-filter

forEach in Angular filter not returning


I have a filter that converts a BPM integer to the correct latin term.

Initially I had an if else statement for each latin term but now am refactoring to be slightly more maintainable.

Here is what I have come up with:

angular.module('app').filter('latinTerm', function() {
    var terms = [
        {
            min: 0,
            max: 41,
            term: "Grave"
        },
        {
            min: 40,
            max: 60,
            term: "Largo"
        },
        {
            min: 59,
            max: 66,
            term: "Larghetto"
        }
    ]

    return function(value) {
        angular.forEach(terms, function(term) {
            if (value > term.min && value < term.max) {
                return value;
            }
        });
    }
});

But this doesn't return anything, even when the value is between the values provided.

Am I using the filter wrong in this sense? Or can it be adjusted to work?

Thanks.


Solution

  • You can't use forEach when you need to break the loop and return something since it doesn't break. You can though use old fashioned for loop to achieve it.

    Quoting Array.prototype.forEach | MDN,

    There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool, use a plain loop instead.

    Something like this:

    angular.module('app').filter('latinTerm', function() {
        var terms = [
            {
                min: 0,
                max: 41,
                term: "Grave"
            },
            {
                min: 40,
                max: 60,
                term: "Largo"
            },
            {
                min: 59,
                max: 66,
                term: "Larghetto"
            }
        ]
    
        return function(value) {
            for(var i = 0; i < terms.length; i++) {
                if (value > terms[i].min && value < terms[i].max) {
                    return value;
                }
            }
        }
    });