Range Over Channels in ActionScript

Our example will demonstrate how to iterate over values received from a channel-like structure in ActionScript. Since ActionScript doesn’t have built-in channels, we’ll simulate this behavior using an Array and a custom Queue class.

package {
    import flash.display.Sprite;
    import flash.utils.setTimeout;

    public class RangeOverChannels extends Sprite {
        public function RangeOverChannels() {
            var queue:Queue = new Queue();
            
            // We'll iterate over 2 values in the queue.
            queue.enqueue("one");
            queue.enqueue("two");
            queue.close();

            // This loop iterates over each element as it's
            // received from queue. Because we closed the
            // queue above, the iteration terminates after
            // receiving the 2 elements.
            for each (var elem:String in queue) {
                trace(elem);
            }
        }
    }
}

class Queue {
    private var items:Array = [];
    private var closed:Boolean = false;

    public function enqueue(item:*):void {
        if (!closed) {
            items.push(item);
        }
    }

    public function close():void {
        closed = true;
    }

    public function get iterator():* {
        return {
            next: function():* {
                if (items.length > 0) {
                    return { value: items.shift(), done: false };
                } else if (closed) {
                    return { value: undefined, done: true };
                } else {
                    // Simulate waiting for more items
                    return new Promise(function(resolve:Function):void {
                        setTimeout(function():void {
                            resolve(iterator.next());
                        }, 100);
                    });
                }
            }
        };
    }
}

To run this ActionScript code, you would typically compile it into a SWF file and run it in a Flash Player or AIR runtime environment. The output would be:

one
two

This example demonstrates a way to simulate channel-like behavior in ActionScript. We’ve created a Queue class that mimics some of the behavior of a channel, including the ability to close it and iterate over its elements.

The for each loop in ActionScript is used to iterate over the elements in the queue, similar to how the range loop is used in the original example. The Queue class implements a custom iterator that allows this iteration to work.

This example also shows that it’s possible to close a non-empty queue but still have the remaining values be received, mirroring the behavior of the original channel example.