A while back, I went through these exercises about functional programming in JS and since then I strive to use those techniques whenever possible. Bear in mind that functional techniques can lead to slower code, since a function call is made for each iteration instead of just running code within a loop block, but hopefully it is easier to work with each array element in that fashion - e.g. would you read/type if($rootScope.watchlist[i]['id'] == titleID) {
or if(element['id'] == titleID) {
?
After reading Igor's answer as well as this article about break
with respect to functional programming, I believe the following should work:
$rootScope
.watchlist
.slice() // copy before reverse(), because reverse() is mutating
.reverse()
.some(function(element, i) {
if(element['id'] == titleID) {
$rootScope.watchlist.splice($rootScope.watchlist.length - 1 - i, 1);
return true;
}
});
Edit:
Igor suggests simplifying that callback passed to some()
. You can use an ES-6 arrow function and a ternary operator to eliminate a few lines, like this:
.some((element, i) => (element['id'] == titleID)? $rootScope.watchlist.splice($rootScope.watchlist.length - 1 - i, 1) : false);
See a demonstration in this plunker. Click the button labeled remove watcher and see how the watcher is removed. This code presumes $rootScope.watchlist
is equivalent to $rootScope.$$watchers
...