Loops' iterating in ANTLR - loops

I'm trying to make a Pascal interpreter using ANTLR and currently have some troubles with processing loops while walking the AST tree.
For example for loop is parsed as:
parametricLoop
: FOR IDENTIFIER ASSIGN start = integerExpression TO end = integerExpression DO
statement
-> ^( PARAMETRIC_LOOP IDENTIFIER $start $end statement )
;
(variant with DOWNTO is ignored).
In what way can I make walker to repeat the loop's execution so much times as needed? I know that I should use input.Mark() and input.Rewind() for that. But exactly where should they be put? My current wrong variant looks so (target language is C#):
parametricLoop
:
^(
PARAMETRIC_LOOP
IDENTIFIER
start = integerExpression
{
Variable parameter = Members.variable($IDENTIFIER.text);
parameter.value = $start.result;
}
end = integerExpression
{
int end_value = $end.result;
if ((int)parameter.value > end_value) goto EndLoop;
parametric_loop_start = input.Mark();
}
statement
{
parameter.value = (int)parameter.value + 1;
if ((int)parameter.value <= end_value)
input.Rewind(parametric_loop_start);
)
{
EndLoop: ;
}
;
(Hope everything is understandable). The condition of repeating should be checked before the statement's first execution.
I tried to play with placing Mark and Rewind in different code blocks including #init and #after, and even put trailing goto to loops head, but each time loop either iterated one time or threw exceptions like Unexpected token met, for example ':=' (assignement). I have no idea, how to make that work properly and can't find any working example. Can anybody suggest a solution of this problem?

I haven't used ANTLR, but it seems to me that you are trying to execute the program while you're parsing it, but that's not really what parsers are designed for (simple arithmetic expressions can be executed during parsing, but as you have discovered, loops are problematic). I strongly suggest that you use the parsing only to construct the AST. So the parser code for parametricLoop should only construct a tree node that represents the loop, with child nodes representing the variables, conditions and body. Afterwards, in a separate, regular C# class (to which you provide the AST generated by the parser), you execute the code by traversing the tree in some manner, and then you have complete freedom to jump back and forth between the nodes in order to simulate the loop execution.

I work with ANTLR 3.4 and I found a solution which works with Class CommonTreeNodeStream.
Basically I splitted off new instances of my tree parser, which in turn analyzed all subtrees. My sample code defines a while-loop:
tree grammar Interpreter;
...
#members
{
...
private Interpreter (CommonTree node, Map<String, Integer> symbolTable)
{
this (new CommonTreeNodeStream (node));
...
}
...
}
...
stmt : ...
| ^(WHILE c=. s1=.) // ^(WHILE cond stmt)
{
for (;;)
{
Interpreter condition = new Interpreter (c, this.symbolTable);
boolean result = condition.cond ();
if (! result)
break;
Interpreter statement = new Interpreter (s1, this.symbolTable);
statement.stmt ();
}
}
...
cond returns [boolean result]
: ^(LT e1=expr e2=expr) {$result = ($e1.value < $e2.value);}
| ...

Just solved a similar problem, several points:
Seems you need to use BufferedTreeNodeStream instead of CommonTreeNodeStream, CommonTreeNodeStream never works for me (struggled long time to find out)
Use seek seems to be more clear to me
Here's my code for a list command, pretty sure yours can be easily changed to this style:
list returns [Object r]
: ^(LIST ID
{int e_index = input.Index;}
exp=.
{int s_index = input.Index;}
statements=.
)
{
int next = input.Index;
input.Seek(e_index);
object list = expression();
foreach(object o in (IEnumerable<object>)list)
{
model[$ID.Text] = o;
input.Seek(s_index);
$r += optional_block().ToString();
}
input.Seek(next);
}

Related

QS5026 - The variable cannot be reassigned here

I'm following tutorial from the official Microsoft learning page (https://learn.microsoft.com/en-us/azure/quantum/tutorial-qdk-explore-entanglement?pivots=ide-azure-portal) about quantum entanglement.
Basically, I copied an example posted there and I am getting error:
QS5026 The variable "numOnesQ1" cannot be reassigned here. In conditional blocks that depend on a measurement result, the target QuantinuumProcessor only supports reassigning variables that were declared within the block.
I understand what it says but it's just a copy from the official Microsoft tutorial. Am I missing something simple like imports, wrong settings? If not, how can I in other way set variables declared outside conditional blocks that depend on a measurement result?
Here is my code:
namespace Quantum.QuantumDream {
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Intrinsic;
operation GetRandomResult() : Result {
use q = Qubit();
H(q);
return M(q);
}
#EntryPoint()
operation TestBellState(count : Int, initial : Result) : (Int, Int, Int, Int) {
mutable numOnesQ1 = 0;
mutable numOnesQ2 = 0;
// allocate the qubits
use (q1, q2) = (Qubit(), Qubit());
for test in 1..count {
SetQubitState(initial, q1);
SetQubitState(Zero, q2);
// measure each qubit
let resultQ1 = M(q1);
let resultQ2 = M(q2);
// Count the number of 'Ones':
if resultQ1 == One {
set numOnesQ1 += 1;
}
if resultQ2 == One {
set numOnesQ2 += 1;
}
}
// reset the qubits
SetQubitState(Zero, q1);
SetQubitState(Zero, q2);
// Return number of |0> states, number of |1> states
Message("q1:Zero, One q2:Zero, One");
return (count - numOnesQ1, numOnesQ1, count - numOnesQ2, numOnesQ2 );
}
operation SetQubitState(desired : Result, target : Qubit) : Unit {
if desired != M(target) {
X(target);
}
}
}
This tutorial code is only supposed to run on a local simulator (using %simulate magic commands in a Jupyter Notebook). From the error message, it looks like you've tried to run it on one of Quantinuum targets, which have some limitations on the kinds of things you can do in the code. To run equivalent code on Quantinuum, you'd need to define an operation for just the body of the loop (preparing a state and measuring it) and run it as a job - the cloud targets will take care of the loop themselves, running your code multiple times and returning to you a histogram of the results. For an example, you can see the QRNG sample in the samples gallery in Azure Portal.

looping multiple vectors in a for loop

I'm programming an objloader and this is a small part of its code.I want to be able to loop through different vectors in a single for loop.The for loop doesn't work here but is it possible to implement this concept somehow? make the (for ((GLdouble* val : container)&&(GLdouble* val2:NContainer)) condition work somehow?
aclass e;
std::vector<GLdouble*> container = e.function();
Nclass n;
std::vector<GLdouble*> Ncontainer = n.function();
for ((GLdouble* val : container)&&(GLdouble* val2:NContainer))
{
glVertex3dv(val);
glNormal3dv(val2);
}

What exactly does the outermost visit strategy do in Rascal?

I wrote the below Rascal code that is supposed to build a tree out of a map from node names to nodes, starting at the node mapped from "top". It should repeatedly replace the children of all nodes that have strings as children in result by the nodes nodeMap maps them to, until nothing changes anymore (fixpoint).
getNode returns the node a map[str,node] maps it to, or the key itself if it is not present as a key in the map. This works fine, as proves the fact that other code at the bottom of this question does work. However, the code directly below seems to run infintely even on very small inputs.
node nodeMapToNode(map[str, node] nodeMap) {
node result = nodeMap["top"];
return outermost visit(result) {
case node n: {
if ([*str children] := getChildren(n)) {
insert makeNode(getName(n), [getNode(child, nodeMap) | child <- children]);
}
}
}
}
The following code does work and returns in an instant on small inputs as I expected. This is, however, exactly what I understood outermost-visiting should do from what I understood from the Rascal tutor.
Can anyone explain to me what the difference between these code snippets is (besides the way they are written) and what I thus misunderstood about the effect of outermost visit? Also, I'd like to know if a shorter and/or nicer way to write this code - using something like outermost-visiting instead of writing the fixpoint by hand - does exist.
node nodeMapToNode(map[str, node] nodeMap) {
node result = nodeMap["top"];
node lastResult;
do {
lastResult = result;
result = visit(lastResult) {
case node n: {
if ([*str children] := getChildren(n)) {
insert makeNode(getName(n),
[getNode(child, nodeMap) | child <- children]);
}
}
}
} while (result != lastResult);
return result;
}
What is outermost?
The rascal tutor is very compact in it's explanation but let's start from there.
repeat a top-down traversal as long as the traversal changes the resulting value (compute a fixed-point).
which in rascal terms means that this:
r = outermost visit(x) {
case str s => s + "."
when size(s) < 3
};
is syntactic sugar for:
r = x;
solve(r) {
r = top-down visit(r) {
case str s => s + "."
when size(s) < 3
};
}
I think there are two common cases were outermost/innermost makes sense:
your replacement should be repeated multiple times on the same node
your replacement generate new nodes that match other patterns
Your specific example
Regarding the example in your question. The other manually rewritten outermost is actually an innermost. The default visit strategy is bottom-up.
In general, an bottom-up visit of the tree is a quicker than a top-down. Especially when you are rewriting it, since Rascal is immutable, building a new tree bottom-up is quicker.
So, perhaps replace your code with an innermost visit instead of an outermost?

Elegant way for do ... while in groovy

How to do code something like this in groovy?
do {
x.doIt()
} while (!x.isFinished())
Because there is no do ... while syntax in groovy.
No 'do ... while()' syntax as yet.
Due to ambiguity, we've not yet added support for do .. while to Groovy
References:
groovy - dev > do while
Migration From Classic to JSR syntax
Groovy Documentation > Control Structures > Looping
Rosetta Code > Loops/Do-while Groovy
You can roll your own looping that's almost what you want.
Here's an example with loop { code } until { condition }
You can't have a corresponding loop { code } while { condition } because while is a keyword.
But you could call it something else.
Anyway here's some rough and ready code for loop until.
One gotcha is you need to use braces for the until condition to make it a closure.
There may well be other issues with it.
class Looper {
private Closure code
static Looper loop( Closure code ) {
new Looper(code:code)
}
void until( Closure test ) {
code()
while (!test()) {
code()
}
}
}
Usage:
import static Looper.*
int i = 0
loop {
println("Looping : " + i)
i += 1
} until { i == 5 }
So many answers and not a single one without a redundant call, a shame ;)
This is the closest it can get to purely language syntax based do-while in Groovy:
while ({
x.doIt()
!x.isFinished()
}()) continue
The last statement within curly braces (within closure) is evaluated as a loop exit condition.
Instead of continue keyword a semicolon can be used.
Additional nice thing about it, loop can be parametrized (kind of), like:
Closure<Boolean> somethingToDo = { foo ->
foo.doIt()
!foo.isFinished()
}
and then elsewhere:
while (somethingToDo(x)) continue
Formerly I've proposed this answer over here: How do I iterate over all bytes in an inputStream using Groovy, given that it lacks a do-while statement?
Depending on your use case, there are options like this: do .. while() in Groovy with inputStream?
Or you can do:
x.doIt()
while( !x.finished ) { x.doIt() }
Or
while( true ) {
x.doIt()
if( x.finished ) break
}
You can use a condition variable with the regular while loop:
def keepGoing = true
while( keepGoing ){
doSomething()
keepGoing = ... // evaluate the loop condition here
}
Update Groovy 2.6 has been abandoned to concentrate on 3.0.
From Groovy 2.6 on, do-while is supported when enabling the new Parrot Parser, from Groovy 3.0 on this is the default. See release notes:
// classic Java-style do..while loop
def count = 5
def fact = 1
do {
fact *= count--
} while(count > 1)
assert fact == 120
By now, Groovy has support for do/while:
do {
x.doIt()
} while (!x.isFinished())
Or you can implement it in a Groovier way :
def loop(Closure g){
def valueHolder = [:]
g.delegate = valueHolder
g.resolveStrategy = Closure.DELEGATE_FIRST
g()
[until:{Closure w ->
w.delegate = valueHolder
w.resolveStrategy = Closure.DELEGATE_FIRST
while(!w()){
g()
}
}]
}

Which is better practice - for loop with break or conditional loop? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm just curious what peoples' thoughts are on this topic. Let's say I have an Array of Objects, and I want to loop through them to see if the Objects contain certain values, and if so, I want to stop the loop. Which is better practice - a for loop with a break, or a conditional loop?
The pseudo-code in the example I have provided is for argument's sake only (it is also in ActionScript, since that is my primary language of late). Also, I am not looking for best practice ideas on syntax.
for loop with break:
var i:int;
var isBaxterInMilwaukee:Boolean;
for (i = 0; i < arrayLen; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
break;
}
}
conditional loop:
var i:int;
var isBaxterInMilwaukee:Boolean;
while (!isBaxterInMilwaukee && i < arrayLen)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
i++;
}
In short, you should go with whichever version is the easiest to read and maintain.
In slightly older times, I know breaking out of a loop was considered to be a no-no (on par with a goto statement). Loops were supposed to break on the loop condition and nowhere else. Thus, the while-loop would have been the way to go.
(This is probably a holdover from assembly, where loops are basically a block of code with a go-to-the-beginning-if-true jump statement at the end. Multiple conditional-jump statements in the block make it exceedingly hard to debug; thus they were to be avoided and combined into one at the end.)
I feel this idea seems to be changing a bit today, especially with foreach loops and the managed world; it's really a matter of style now. Break-on-found for-loops have perhaps come to be acceptable to many, save some purists of course. Note that I would still avoid using break in a while-loop, however, as this can muddle the loop condition and make it confusing.
If you'll allow me to use a foreach loop, I consider the code below to be a lot easier to read than its while-loop brother:
bool isBaxterInMilwaukee;
foreach (var item in myArray)
{
if (item.name == "baxter" && item.location == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
break;
}
}
However, as the logic grows in complexity, you may want to consider a prominent comment near the break statement lest it become buried and hard to find.
Arguably, this whole thing should be refactored into its own function which doesn't break on found, but actually returns the result (feel free to use the for-loop version instead):
bool isBaxterInMilwaukee(Array myArray)
{
foreach (var item in myArray)
{
if (item.name == "baxter" && item.location == "milwaukee")
{
barkTwice();
return true;
}
}
return false;
}
As Esko Luontola pointed out, it would probably be best to move the call to barkTwice() outside of this function as the side-effect is not evident from the function's name, nor related to finding Baxter in every case. (Or add a boolean parameter BarkTwiceIfFound and change the line to read if(BarkTwiceIfFound) barkTwice(); to make the side-effect clear.)
For the record, you can also do the flag check in the for-loop without a break, but I feel this actually hurts readability because you don't expect an extra condition in a for-loop definition:
var i:int;
var isBaxterInMilwaukee:Boolean;
for (i = 0; !isBaxterInMilwaukee && i < arrayLen; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
You can also simulate auto-incrementing mechanics with a while-loop. I don't like this for a few reasons - you have to initialize i to be one less than your real starting value, and depending on how your compiler short-circuits the loop-condition logic, your value of i on exiting the loop may vary. Nevertheless, it is possible and for some people, this can improve readability:
var i:int = -1;
var isBaxterInMilwaukee:Boolean;
while (!isBaxterInMilwaukee && ++i < arrayLen)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
I've always disliked the use of breaks in code... In this case it doesn't seem to matter but on more involved loops, it can be awfully confusing to another coder reading it. In general, it often results in not understanding how the loop may terminate until the coder spots the nested break deep in the loop. By specifying a flag condition that's checked each iteration of the loop, it makes this much clearer.
This problem would be similar to having return statements that are deep in the body of a method where they're not easily spotted (rather than setting a retVal variable and returning at the end of the method). With a small method, this seems fine, but the bigger it gets, the more confusing this will be.
It's not an efficiency of operation thing, it's a maintainability thing.
Ask your coworkers what's readable and understandable for a particular situation... That's what really matters.
I would say it depends. In this case the loop with the break seems clearer to me.
In a for loop you can also early exit by putting the early exit criteria in the for loop declaration. So for your example you could do it this way:
var i:int;
var isBaxterInMilwaukee:Boolean;
isBaxterInMilwaukee = false;
for (i = 0; i < arrayLen && !isBaxterInMilwaukee; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
That way you don't need a break, and it's still more readable than a while loop.
There is a conceptual difference between the two. for loops are for iterating over discrete sets and while loops are for repeating statements based on a condition. Other languages add in finally clauses and looping constructs like foreach or until. They tend to have considerably fewer traditional for loops.
In any case, the rule that I use is that for loops iterate and while loops repeat. If you see something like:
while (counter <= end) {
// do really cool stuff
++counter;
}
Then you are probably better off with a for loop since you are iterating. However, loops like:
for (int tryCount=0; tryCount<2; ++tryCount) {
if (someOperation() == SUCCESS) {
break;
}
}
should be written as while loops since they are really repeating something until a condition is true.
The thought of not using break since it is just as evil as goto is pretty nonsensical. How can you justify throwing an exception then? That's just a non-local and non-deterministic goto! By the way, this isn't a rant against exception handling, just an observation.
The one that makes the most sense is going to be the one that conveys the idea to the human reading the code the best. Remember code readability first, and you'll usually make the correct choice. Usually, you do not want to use something like break unless you really need to, because it can make things hard to follow if done often or even just in a deeply-nested set of expressions. continue can serve the same purpose as a break sometimes, and the loop will then exit normally instead of because it was broken. In this case, there are a couple of different ways I might write this.
Probably the best thing you want here is a modification of your while loop:
while(!isBaxterInMilwaukee || i < arrayLen) {
if(myArray[i]["name"] == "baxter" && myArray[i]["location"] == "milwaukee") {
isBaxterInMilwaukee == true;
barkTwice()
} else {
i++;
}
}
That's clear and doesn't use break or continue, so you can tell at a glance that you'll always terminate as a result of one of the conditions specified in the while expression.
ETA: Probably should be i < arrayLen in the while loop otherwise it fails the first time through unless the input value is the same as the target value...
I see the break in both loops, is that correct?
Anyway:
I would choose FOR loop when there is known number (maximum number) of iterations before loop starts.
I would choose WHILE otherwise.
In FOR loop I use BREAK freely.
In WHILE loop I prefer to use complex condition instead of BREAK (if it is possible).
I would say break, clearer (even if you put in a comment why you break out of the loop)
Imho the while loop is not clear, i would go for break
I would definitely go with the for+break. The ‘for’ is an instantly-recognisable idiom for “iterate over sequence” and it's easier to understand “iterate over sequence; end early if value found” than the combined loop-and-stop condition.
There may be evidence for this in the way you seem to have made two mistakes in your conditional loop code!
the while condition (!isBaxterInMilwaukee || i == arrayLen) — did you mean “(!(isBaxterInMilwaukee || i == arrayLen))”?
break statement is unnecessary if you're using a terminate-loop variable.
Personally I find a simple ‘break’ much easier to read than trying to track a terminate-loop variable.
There are two aspects of the problem:
What to do (eg: find if one of the items contain the specified person in the location)
How to do it (eg: use an index, iterate etc)
Both of the examples mix the two and is hard to understand the what from the how. The best would be if we could express in code only the what part. Here is an example (c# 3.5) that does this using the specification pattern
// what we are looking for?
IsPersonInLocation condition = new IsPersonInLocation("baxter", "milwaukee");
// does the array contain what we are looking for?
bool found = myArray.Find(item => condition.IsSatifiedBy(item));
// do something if the condition is satisfied
if (found) {
barkTwice();
}
For completeness here is the class definition for the condition:
class IsPersonInLocation {
public string Person { get; set; }
public string Location { get; set; }
public IsPersonInLocation(string person, string location) {
this.Person = person;
this.Location = location;
}
bool IsSatifiedBy(item) {
return item["name"] == this.Person
&& item["location"] == this.Location;
}
}
It depends a lot on what the specific circumstances are. But in your example, you want to walk an array of bounded length, and using a for loop makes it easy to do that and guard against running off the end. In your while loop example you have to do your own incrementing--which can be problematic if you wanted to use a continue statement to skip into the next cycle--and make a more complex conditional expression (which, by the way, has a bug; I think you meant && i != arrayLen ). You're just having to do extra code to accomplish the effect that for loops help provide.
Of course, some purists will argue that break and continue should not be used and that you should use if-else and boolean variables if needed rather than continue or break out of a loop. But I think that can make the loop look much more ugly, especially if its relatively short and easy to grasp in general like this example. For a loop with much longer code where a break or continue could easily hide from notice, the purist approach might be more clear, since the loop is already complicated to grasp in that case. But you can always do this as part of the for loop, just add it as part of the conditional.
It's also better practice to test the array bound with i < arrayLen rather than for an exact equality, in case something caused i to skip over the exact value (I actually saw this happen in a Y2K bug, which could have been avoided by the better practice).
I have a C++ background and so I still have moments where I try to "think like the compiler". While loops tend to result in tighter code, and so for loops were only ever considered if you knew you were going to iterate over every element in the array, every time.
EDIT: I now believe this is overkill, if you're using .Net or whatever you aren't going to make up for the VM overhead with a couple of tight loops. I do think remembering the "why" of certain practices is a good thing though.
My theory is that there is a useful programming abstraction similar to "signal-to-noise ratio", which is "problem-to-tool ratio" - goodness can be measured in one dimension by how much time I spend thinking about the problem and its solution, compared to the time I spend thinking about how to use the tool (in this case language syntax).
By that measure, I try to use fewer constructs more frequently, because I (and hopefully those who follow) can grok the essence of my code structure more quickly and accurately. And since variations of "for loops" do a pretty good job of covering the cases where the others might be used (without distortion), I use them as a first preference, when they are interchangeable.
And it's nice to have everything you need to know (grokwise) about the loops rules in a single line at the top of the "for" loop. I also tend to put the "default" switch first in the tests for the same reason.
But consistency and clarity is the ovveriding consideration. YMMV, of course.
I guess neither is actually vary interesting. You should look for higher level constructs if it's readability you're after.
In JS:
if(myArray.some(function(o) { o.name == "baxter" && o.location == "milwaukee" }))
barkTwice();
or with some utils of your own
if(myArray.containsMatch({name:"baxter",location:"milwaukee"})
barkTwice();
Encapsulate the loop in its own method and use return to end processing when your match condition has succeeded.
Some example C# code:
class Program
{
static bool IsBaxterInMilwaukee(IList<WhoAndWhere> peopleAndPlaces)
{
foreach (WhoAndWhere personAndPlace in peopleAndPlaces)
{
if (personAndPlace.Name == "Baxter"
&& personAndPlace.Location == "Milwaukee")
{
return true;
}
}
return false;
}
static void Main(string[] args)
{
List<WhoAndWhere> somePeopleAndPlaces = new List<WhoAndWhere>();
somePeopleAndPlaces.Add(new WhoAndWhere("Fred", "Vancouver"));
somePeopleAndPlaces.Add(new WhoAndWhere("Baxter", "Milwaukee"));
somePeopleAndPlaces.Add(new WhoAndWhere("George", "London"));
if (IsBaxterInMilwaukee(somePeopleAndPlaces))
{
// BarkTwice()
Console.WriteLine("Bark twice");
}
}
public class WhoAndWhere
{
public WhoAndWhere(string name, string location)
{
this.Name = name;
this.Location = location;
}
public string Name { get; private set; }
public string Location { get; private set; }
}
}
My general stance is:
If it has a loop counter use for() (like while while loop does).
I vote while because breaks reduce grokability.
You may not realize the loop contains a break if the loop has grown too long and you insert code you expect to run and it does not.
But I subscribe to the don't make me think model of coding.
In ES6, it has been made very easy, no need to use the break keyword, We can use the find function, once the condition satisfies, we can return true.
let barkTwice = () => {
console.log('bark twice');
}
let arr = [{
location: "waukee",
name: "ter"
}, {
location: "milwaukee",
name: "baxter"
},
{
location: "sample",
name: "sampename"
}
];
Here we matching the condition and once the condition matches, we are calling the function, as per the question and then we are returning true. So that it does not go beyond.
arr.find(item => {
if (item.location == "milwaukee" && item.name == "baxter") {
barkTwice();
return true
}
});

Resources