December 9, 2020
Iterator Support in ColdFusion 2021
Comments
(0)
December 9, 2020
Iterator Support in ColdFusion 2021
Newbie 1 posts
Followers: 0 people
(0)

An Iterable is any object, not necessarily a data structure, that can return an iterator (with the purpose of returning all its elements).  Using an iterable one can create multiple iterators and do iteration independently. Once iterator is used its not reusable.  Iterator is an instance of current iteration.

ColdFusion Components can be made iterable and UDF’s are used as iterators.  A ColdFusion component that defines an “__iter__ “function which accepts no arguments is iterable.

“_iter_” function will be called to return the iterator instance. The iterable function can return array, String, query, function or object of another component that has a function named __next()__.

Iterable function returning a UDF:

component {
public any function __iter__() {
var startFrom = 100;
return function(previous, index){//Iterator UDF
return {"value": startFrom + index, "done": index > 9};
}
}
}

Iterable function returning string, string will be treated as an array of characters:

component {
public any function __iter__() {
return "thisisastring";
}
}

Iterable function returning array :

component {
public any function __iter__() {
return [1,2,3,4,5,6];
}
}

Iterable function returning query :

component {
public any function __iter__() {
return QueryExecute(("SELECT * FROM EMPLOYEES WHERE EMP_ID BETWEEN :low AND :high"),{low=4,high=14},
{datasource="cfdocexamples"});
}
}

Iterable function returning object of a CFC that defines a function “_next”:

Iterator.cfc
component {
public any function __next__(previous, count){// Follows Iteration Protocol as UDF
return {value: count+1, done: count > 11};
}
}
component {
public any function __iter__() {
return new iterator();
}
}

Iterators can be invoked either using for in loop or using Spread Operator

Using for-in loop :

Test.cfc:
component {
public any function __iter__() {
return [1,2,3,4,5,6];
}
}
t = new test();
for (i in t) {
writeoutput(i); // 1 2 3 4 5 6
}

Using Spread Operator

t = new test();
b = [11, 12, 13, ...t];
writedump(b) // [11,12,13,1,2,3,4,5,6]

0 Comments
Add Comment