Skip to content

Commit 26ed4a8

Browse files
authored
Create foreach.cls
1 parent a8c575e commit 26ed4a8

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

src/cls/Iteration/foreach.cls

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
Class Iteration.Loop
2+
{
3+
4+
/// Example of how to use the foreach functionality
5+
ClassMethod SampleMethod() As %Status
6+
{
7+
try {
8+
set message = {}
9+
set message.sampleelement = "Dynamic 1"
10+
set message.anothersample = "Dynamic 2"
11+
12+
// Pass the object, the function we want run, and our class location to the foreach
13+
do ..Foreach(.message, "Action")
14+
}
15+
catch(e) {
16+
write "SampleMethod error" _e.Name
17+
}
18+
return $$$OK
19+
}
20+
21+
// Some method that we call on each iteration
22+
ClassMethod Action(pMes) As %Status
23+
{
24+
try {
25+
write pMes, !
26+
}
27+
catch(e) {
28+
write "Foreach action error: " _e.Name
29+
}
30+
return $$$OK
31+
}
32+
33+
/// Takes in our dynamic object or array, the string value name of the function we want to run on
34+
/// each iteration, and an optional value of the class location of our method that's being run on each
35+
/// iteration.
36+
ClassMethod Foreach(ByRef pVal, pFunc, pClass As %String = "") As %Status
37+
{
38+
if 'pClass { set pClass = $this }
39+
try {
40+
if $classname(pVal) = "%Library.DynamicObject" {
41+
// We get the key value pairs from our dynamic object
42+
set tIter = pVal.%GetIterator()
43+
if tIter = "" throw
44+
// Loop through these values and add to our query depending on their contents
45+
while tIter.%GetNext(.key, .value) {
46+
// We pass the value to the action
47+
// TODO: Add ability to capture value and key in a friendly way
48+
do $classmethod(pClass, pFunc, value)
49+
}
50+
}
51+
else {
52+
return $classname(pVal)
53+
}
54+
}
55+
catch (e) {
56+
57+
try {
58+
// Element position init
59+
set tStruct=""
60+
// Loop through the array
61+
for {
62+
set tStruct=$order(pVal(tStruct))
63+
quit:tStruct=""
64+
// Perform our action method on each element
65+
do $classmethod(pClass, pFunc, pVal(tStruct))
66+
}
67+
}
68+
catch (e) {
69+
write "Foreach error " _e.Name
70+
}
71+
72+
w e.Name
73+
}
74+
return $$$OK
75+
}
76+
77+
}

0 commit comments

Comments
 (0)