Reputation: 8075
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.
Upvotes: 1
Views: 2437
Reputation: 1386
If you still need to use angular.forEach (it happens), just use a variable:
return function(value) {
var returnValue;
angular.forEach(terms, function(term) {
if (value > term.min && value < term.max) {
returnValue = value;
}
});
return returnValue;
}
Upvotes: 2
Reputation: 7911
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;
}
}
}
});
Upvotes: 4
Reputation: 41387
you can't return inside foreach because it will not break inside for each. one thing you can do is assign value to variable based on the condition or use for loop
angular.module("app",[])
.controller("ctrl",function($scope){
$scope.values = [21,331,12,44,1111]
}).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) {
var result = [];
angular.forEach(terms, function(term) {
if (value > term.min && value < term.max) {
result.push( value);
}
});
return result[0]
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<div ng-repeat="item in values">{{item | latinTerm}}</div>
</div>
Upvotes: 0