-
Do we have iterators in Ballerina or something similar? So that a module writer can return an iterable object that can be directly used with a loop. Sample use from TypeScript GitHub client. (Which is using async iterator) const iterator = octokit.paginate.iterator(octokit.rest.issues.list, {
owner: config.repoOwner,
repo: config.controlPlaneRepo,
state: 'open',
labels: 'Type/Bug'
});
for await (let page of iterator) {
for (let issue of page.data) {
const issueNumber = issue.number;
// Logic goes here...
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Yes. An object can make itself iterable by using type inclusion with import ballerina/io;
class Store {
*object:Iterable;
Configuration[] arr = [];
public function iterator() returns
object { public function next() returns
record {| record {| int id; anydata value; |} value; |}?; } {
return new EnabledConfigIterator(self.arr);
}
}
public class EnabledConfigIterator {
private record {| int id; anydata value; |}[] details;
private int index = 0;
function init(Configuration[] arr) {
self.details = arr.filter(c => c.enabled).map(c => {id: c.id, value: c.value});
}
public function next() returns record {| record {| int id; anydata value; |} value; |}? {
if self.index == self.details.length() {
return; // End of iteration indicated by `()`.
}
var rec = self.details[self.index];
self.index += 1;
return {value: rec};
}
}
type Configuration record {|
int id;
anydata value;
boolean enabled;
|};
public function main() {
Store store = new;
store.arr.push({id: 123, enabled: true, value: 1.0},
{id: 234, value: "max", enabled: false},
{id: 345, value: 2, enabled: true});
// The subtype of `object:Iterable<T, ()>` can directly be used in a `foreach` statement.
foreach var item in store {
io:println(item.id);
}
} There can also be |
Beta Was this translation helpful? Give feedback.
Yes. An object can make itself iterable by using type inclusion with
object:Iterable
(i.e., subtype ofIterable<T,C>
) and defining aniterator
method that returns an iterator object (i.e., subtype ofIterator<T,C>
).