working on it ...

## Filters

Sort by

Found 662 snippets matching: iterator

### emca6 infinitely cycle through values in Set using a generator and iterator

emca6 infinitely cycle through values in Set using a generator and iterator: lazy-infinite-loop-set.js
```"use strict";

// generator to infinitely loop over a set
let infiniteCycleSet = function* ( set ){
let _seq = set.values()
while( true ){
let _cur = _seq.next()
if( _cur.done ){
_seq = set.values()
_cur = _seq.next()
}
yield _cur.value
}
}

// generator to infinitely loop over a set
// starting from a specific value
let infiniteCycleSetFrom = function* ( set, startAt ){
let _seq = set.values(), _target = startAt
while( true ){
let _cur = _seq.next()
if( _cur.done ){
_seq = set.values()
_cur = _seq.next()
}
if( _cur.value === _target ){
let _next = _seq.next()
if( _next.done ){
_seq = set.values()
_next = _seq.next()
}
_target = _next.value
yield _target
}
}
}

```

### Enumerator.js... behind every enumeration you'll find a good Iterator. I guess.... LoL

the future is now!
```// slick as snot Enumerable type!!!! yeah!

var Enum = {
create: function (collection) {
var index=0;
return {
next: function() {
if (index < collection.length) {
return ({ value: collection[index++], done: false });
}
else {
return ({ value: null, done: true});
}
}
};
}
};

// use it like this... (strings, bool, numbers, all gewd!)

var arr=['rtJKvE', '!!@wrh', 433, 'yippe', 216,'PRdUrg', 3038, 'whaa?'],
it = Enumerator.create(arr),
primer = 0;

while(primer !== null) {
primer = it.next().value;
document.writeLine(primer);
}
```

### Typescript + underscore: iterating through a collection property of a class

In this example we define a signature interface (Students) to locate a student using a student ID. In the Course class we use property getters function to provide read only access to the class members. Finally we use underscore to iterate on the Students as it was an array. The example runs on node.js with Typescript 0.9.5
```///<reference path='../types/node.d.ts'/>
///<reference path='../types/underscore.d.ts'/>

import _ = require("underscore");

function write(msg) {
process.stdout.write(msg+'\n');
}
// Index Interface to locate a student given an id
interface Students {
[ studentId: number ] : Student;
}

class Student {
private _id : number;
private _name : string;
private _lastName : string;
constructor ( id: number, name : string, lastName : string ) {
this._id = id;
this._name = name;
this._lastName = lastName;
}
// Property getters for Student
get id() :number { return this._id; }
get lastName() : string { return this._lastName; }
}

class Course {
private title : string;
_participants : Students = {};

constructor( t : string ) {
this.title = t;
}

this._participants[s.id] = s;
}
getStudent( sid: number ) : Student {
return this._participants[sid];
}

// Property getter to retrieve the participants of a Course
get participants() {
return _.values(this._participants)
}

}

var c = new Course("Computer Science 101");

_.each( c.participants , (s : Student) => write(s.lastName));
```

### Interator to stream in Java 8

makes a java 8 stream from an iterator
```//this method converts a iterator to a stream. This can only be used in Java 8
public static <T> Stream<T> iteratorToStream(final Iterator<T> iterator, final boolean parallell) {
Iterable<T> iterable = () -> iterator;
return StreamSupport.stream(iterable.spliterator(), parallell);
}

//here I show you how to use this method. You need this try arround it so Java will close the stream automatically after using it.
try (Stream<???> stream = Utils.<???>iteratorToStream(anIterator, true)) {

}```

#### public by msdn  2742  0  6  0

Adds TableCell elements to xamlTableRowElement. XmlElement representing Xaml TableRow element to which the converted cells should be added XmlElement representing the child of tr or tbody element from which we should start adding td elements properties of the current html tr element to which cells are to be added XmlElement re
```public const string Xaml_TableRow = "TableRow";
public const string Xaml_TableCell = "TableCell";
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
static string _xamlNamespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
public const string Xaml_TableCell_ColumnSpan = "ColumnSpan";

/// <summary>
/// Adds TableCell elements to xamlTableRowElement.
/// </summary>
/// <param name="xamlTableRowElement">
/// XmlElement representing Xaml TableRow element to which the converted cells should be added
/// </param>
/// <param name="htmlTDStartNode">
/// XmlElement representing the child of tr or tbody element from which we should start adding td elements
/// </param>
/// <param name="currentProperties">
/// properties of the current html tr element to which cells are to be added
/// </param>
/// <returns>
/// XmlElement representing the current position of the iterator among the children of the parent Html tbody/tr element
/// </returns>
private static XmlNode AddTableCellsToTableRow(XmlElement xamlTableRowElement, XmlNode htmlTDStartNode, Hashtable currentProperties, ArrayList columnStarts, ArrayList activeRowSpans, CssStylesheet stylesheet, List<XmlElement> sourceContext)
{
// parameter validation
Debug.Assert(xamlTableRowElement.LocalName == Xaml_TableRow);
Debug.Assert(currentProperties != null);
if (columnStarts != null)
{
Debug.Assert(activeRowSpans.Count == columnStarts.Count);
}

XmlNode htmlChildNode = htmlTDStartNode;
double columnStart = 0;
double columnWidth = 0;
int columnIndex = 0;
int columnSpan = 0;

while (htmlChildNode != null && htmlChildNode.LocalName.ToLower() != "tr" && htmlChildNode.LocalName.ToLower() != "tbody" && htmlChildNode.LocalName.ToLower() != "thead" && htmlChildNode.LocalName.ToLower() != "tfoot")
{
if (htmlChildNode.LocalName.ToLower() == "td" || htmlChildNode.LocalName.ToLower() == "th")
{
XmlElement xamlTableCellElement = xamlTableRowElement.OwnerDocument.CreateElement(null, Xaml_TableCell, _xamlNamespace);

Hashtable tdElementLocalProperties;
Hashtable tdElementCurrentProperties = GetElementProperties((XmlElement)htmlChildNode, currentProperties, out tdElementLocalProperties, stylesheet, sourceContext);

// TODO: determine if localProperties can be used instead of htmlChildNode in this call, and if they can,
// make necessary changes and use them instead.
ApplyPropertiesToTableCellElement((XmlElement)htmlChildNode, xamlTableCellElement);

if (columnStarts != null)
{
Debug.Assert(columnIndex < columnStarts.Count - 1);
while (columnIndex < activeRowSpans.Count && (int)activeRowSpans[columnIndex] > 0)
{
activeRowSpans[columnIndex] = (int)activeRowSpans[columnIndex] - 1;
Debug.Assert((int)activeRowSpans[columnIndex] >= 0);
columnIndex++;
}
Debug.Assert(columnIndex < columnStarts.Count - 1);
columnStart = (double)columnStarts[columnIndex];
columnWidth = GetColumnWidth((XmlElement)htmlChildNode);
columnSpan = CalculateColumnSpan(columnIndex, columnWidth, columnStarts);
int rowSpan = GetRowSpan((XmlElement)htmlChildNode);

// Column cannot have no span
Debug.Assert(columnSpan > 0);
Debug.Assert(columnIndex + columnSpan < columnStarts.Count);

xamlTableCellElement.SetAttribute(Xaml_TableCell_ColumnSpan, columnSpan.ToString());

// Apply row span
for (int spannedColumnIndex = columnIndex; spannedColumnIndex < columnIndex + columnSpan; spannedColumnIndex++)
{
Debug.Assert(spannedColumnIndex < activeRowSpans.Count);
activeRowSpans[spannedColumnIndex] = (rowSpan - 1);
Debug.Assert((int)activeRowSpans[spannedColumnIndex] >= 0);
}

columnIndex = columnIndex + columnSpan;
}

if (xamlTableCellElement.HasChildNodes)
{
xamlTableRowElement.AppendChild(xamlTableCellElement);
}

Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlChildNode);
sourceContext.RemoveAt(sourceContext.Count - 1);

htmlChildNode = htmlChildNode.NextSibling;
}
else
{
// Not td element. Ignore it.
// TODO: Consider better recovery
htmlChildNode = htmlChildNode.NextSibling;
}
}
return htmlChildNode;
}```

### AddTableRowsToTableBody: Adds TableRow elements to xamlTableBodyElement. The rows are converted from Html tr elements that may be the children of an Html tbody element or an Html table element with tbody missing

Adds TableRow elements to xamlTableBodyElement. The rows are converted from Html tr elements that may be the children of an Html tbody element or an Html table element with tbody missing XmlElement representing Xaml TableRowGroup element to which the converted rows should be added XmlElement representing the first tr child of the tbody
```public const string Xaml_TableRowGroup = "TableRowGroup";
public const string Xaml_TableRow = "TableRow";
// ---------------------------------------------------------------------
//
// Private Fields
//
// ---------------------------------------------------------------------
static string _xamlNamespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";

/// <summary>
/// Adds TableRow elements to xamlTableBodyElement. The rows are converted from Html tr elements that
/// may be the children of an Html tbody element or an Html table element with tbody missing
/// </summary>
/// <param name="xamlTableBodyElement">
/// XmlElement representing Xaml TableRowGroup element to which the converted rows should be added
/// </param>
/// <param name="htmlTRStartNode">
/// XmlElement representing the first tr child of the tbody element to be read
/// </param>
/// <param name="currentProperties">
/// Hashtable representing current properties of the tbody element that are generated and applied in the
/// AddTable function; to be used as inheritedProperties when adding tr elements
/// </param>
/// <param name="columnStarts"></param>
/// <param name="stylesheet"></param>
/// <param name="sourceContext"></param>
/// <returns>
/// XmlNode representing the current position of the iterator among tr elements
/// </returns>
private static XmlNode AddTableRowsToTableBody(XmlElement xamlTableBodyElement, XmlNode htmlTRStartNode, Hashtable currentProperties, ArrayList columnStarts, CssStylesheet stylesheet, List<XmlElement> sourceContext)
{
// Parameter validation
Debug.Assert(xamlTableBodyElement.LocalName == Xaml_TableRowGroup);
Debug.Assert(currentProperties != null);

// Initialize child node for iteratimg through children to the first tr element
XmlNode htmlChildNode = htmlTRStartNode;
ArrayList activeRowSpans = null;
if (columnStarts != null)
{
activeRowSpans = new ArrayList();
InitializeActiveRowSpans(activeRowSpans, columnStarts.Count);
}

while (htmlChildNode != null && htmlChildNode.LocalName.ToLower() != "tbody")
{
if (htmlChildNode.LocalName.ToLower() == "tr")
{
XmlElement xamlTableRowElement = xamlTableBodyElement.OwnerDocument.CreateElement(null, Xaml_TableRow, _xamlNamespace);

// Get tr element properties
Hashtable trElementLocalProperties;
Hashtable trElementCurrentProperties = GetElementProperties((XmlElement)htmlChildNode, currentProperties, out trElementLocalProperties, stylesheet, sourceContext);
// TODO: apply local properties to tr element

AddTableCellsToTableRow(xamlTableRowElement, htmlChildNode.FirstChild, trElementCurrentProperties, columnStarts, activeRowSpans, stylesheet, sourceContext);
if (xamlTableRowElement.HasChildNodes)
{
xamlTableBodyElement.AppendChild(xamlTableRowElement);
}

Debug.Assert(sourceContext.Count > 0 && sourceContext[sourceContext.Count - 1] == htmlChildNode);
sourceContext.RemoveAt(sourceContext.Count - 1);

htmlChildNode = htmlChildNode.NextSibling;

}
else if (htmlChildNode.LocalName.ToLower() == "td")
{
// Tr element is not present. We create one and add td elements to it
XmlElement xamlTableRowElement = xamlTableBodyElement.OwnerDocument.CreateElement(null, Xaml_TableRow, _xamlNamespace);

// This is incorrect formatting and the column starts should not be set in this case
Debug.Assert(columnStarts == null);

htmlChildNode = AddTableCellsToTableRow(xamlTableRowElement, htmlChildNode, currentProperties, columnStarts, activeRowSpans, stylesheet, sourceContext);
if (xamlTableRowElement.HasChildNodes)
{
xamlTableBodyElement.AppendChild(xamlTableRowElement);
}
}
else
{
// Not a tr or td  element. Ignore it.
// TODO: consider better recovery here
htmlChildNode = htmlChildNode.NextSibling;
}
}
return htmlChildNode;
}```

### Demonstrate anonymous class nesting from Iterator drop method

Demonstrate anonymous class nesting from Iterator drop method: drop_test.scala
```import java.io.{StringWriter, PrintWriter}
import scala.reflect.ClassTag

def tracehead(e: Exception, substr: String = "slice"): String = {
val sw = new StringWriter()
e.printStackTrace(new PrintWriter(sw))
sw.toString.split('\n').takeWhile((s:String)=> !s.contains(substr)).drop(1).mkString("\n")
}

class TestIterator[T: ClassTag](val iter: Iterator[T]) extends Iterator[T] {
override def hasNext = iter.hasNext
override def next = {
iter.next
}
}

def drop_test[T](itr: Iterator[T]) {
var n = 0
var iter = itr
while (iter.hasNext) {
n += 1
println(s"\ndrop # \$n")
iter = iter.drop(1)
}
}

```

### test: iterator_range & custom iterator

test: iterator_range & custom iterator: range.cc
```#include <iostream>
#include <list>
using namespace std;

template <class Iterator>
struct iterator_range
{
using iterator = Iterator;

iterator_range(iterator _begin, iterator _end)
: _begin{_begin}, _end{_end} {}

const iterator& cbegin() const { cout << "cbegin" << endl; return _begin; }
const iterator& cend() const { return _end; }
iterator& begin() { cout << "begin" << endl; return _begin; }
iterator& end() { return _end; }

private:
iterator _begin;
iterator _end;
};

template <class Iterator>
decltype(auto) make_iterator_range(Iterator begin, Iterator end)
{
return iterator_range<Iterator>(begin, end);
}

struct primitive
{
virtual void render() = 0;
virtual void damage(bool val=true) { _damaged = val; }
virtual bool damaged() { return _damaged; }

private:
bool _damaged = true;
};

struct rect : public primitive
{
rect() { my = i++; }
void render() override { damage(false); cout << "render rect " << my << endl; }

private:
int my;
static int i;
};
int rect::i;

struct fill : public primitive
{
fill() { my = i++; }
void render() override { damage(false); cout << "render fill " << my << endl; }

private:
int my;
static int i;
};
int fill::i;

struct scene
{
using value_type = primitive*;
using  list_type = std::list<value_type>;
using   iterator = list_type::iterator;

struct damaged_iterator
: public std::iterator<std::forward_iterator_tag, value_type>
{
using iterator = scene::iterator;
using self_type = damaged_iterator;

damaged_iterator(iterator c, iterator end) : c(c), end(end)
{
validate();
}

value_type& operator*() { return *c; }

self_type& operator++()
{
++c;
validate();
return *this;
}

bool operator!=(const self_type& other) { return (c != other.c); }

private:
iterator c;
iterator end;

void validate()
{
while (c != end && !(*c)->damaged())
++c;
}
};

using damaged_range = iterator_range<damaged_iterator>;

damaged_range damaged() { return {damaged_begin(), damaged_end()}; }
damaged_iterator damaged_begin() { return {begin(), end()}; }
damaged_iterator damaged_end()   { return {  end(), end()}; }
iterator begin() { return childs.begin(); }
iterator end()   { return childs.end  (); }

void render()
{
for (auto child: damaged())
child->render();
}

iterator rect() { return childs.insert(childs.end(), new ::rect); }
iterator fill() { return childs.insert(childs.end(), new ::fill); }

private:
list_type childs;
};

int main()
{
scene s;
s.rect();
s.rect();
s.fill();
auto r1 = s.rect();
s.rect();
s.fill();
auto r2 = s.fill();
s.rect();
s.fill();
s.fill();
s.render();
(*r1)->damage();
s.render();
s.render();
(*r2)->damage();
s.render();
s.render();
s.render();
}

```

### ES 2015 iterator sample based on http://learn.javascript.ru/iterator

ES 2015 iterator sample based on http://learn.javascript.ru/iterator: es2015-iterator-sample.js
```(function () {
'use strict';

let range = {
from: 1,
to: 5
}

// make object range iterable
range[Symbol.iterator] = function() {

let current = this.from;
let last = this.to;

// method must return object with next()
return {
next() {
if (current <= last) {
return {
done: false,
value: current++
};
} else {
return {
done: true
};
}
}

}
};

for (let num of range) {
console.log(num); // 1, 2, 3, 4, 5
}
})();

```

### ES6 iterator of iterators

ES6 iterator of iterators: iterator_of_iterators.js
```var a = [1, 2];
var b = [3, 4];

var arr = [a, 9, b, "bar"]; // some iterable and non iterable stuff

arr[Symbol.iterator] = function() {
let index = 0;
let that = this;
let current = that[index][Symbol.iterator]();
let isIterable = function(obj) {
if (obj === null) {
return false;
}
return typeof obj[Symbol.iterator] === 'function';
}

return {
next() {
let nextOne = current.next();

// current iterable element is done
if (nextOne.done) {
if (index++ == that.length) {
// must be last element of last iterable so just return it
return nextOne;
}

if (isIterable(that[index])) {
// next element is an iterable, set it and return its next element
current = that[index][Symbol.iterator]();
return current.next();
}

// next element is not iterable but not last element, just return it
return {
done: false,
value: that[index]
};
}

return nextOne;
}
};
};

for (let i of arr) {
console.log("-", i);
}

// - 1
// - 2
// - 9
// - 3
// - 4
// - b
// - a
// - r

```
• Public Snippets
• Channels Snippets