Overview



Algorithm


Given: we have instance variable that is fixed collection named "this.elements"

forEach(actionFct) {
	Iterate over all elements in this.elements (next)
		Simply run actionFct with argument "next"


Pseudocode


Method forEach
  • Method receives actionFct
  • Iterate to nextElem
  • Invoke actionFct with nextElem
/**
 * Iterates over elements in "this" object. For each element,
 * performs actionFct (passing element being iterated on)
*/
forEach(
1
actionFct) { for (let
2
nextElem of this.elements)
3
actionFct(nextElem); }
Try It - forEach
Printing a list has become pretty easy.
class QueryArray {
	static from(elements) {
		return new this(elements);
	}
	constructor(elements) {
		this.elements = elements;
	}
	map(mapFct) {
		let newElements = Array.newDynamic();
		for (let nextElem of this.elements) {
			let newElem = mapFct(nextElem);
			newElements.add(newElem);
		}
		return QueryArray.from(newElements);
	}
	forEach(actionFct) {
		for (let nextElem of this.elements)
			actionFct(nextElem);
	}
	findFirst(matchFct) {
		let elements = this.elements;
		for (let i = 0; i < elements.length; i++) {
			let nextElem = elements.get(i);
			if (matchFct(nextElem))
				return i;
		}
		return -1;
	}
	toString() {
		return this.elements.toString();
	}
	printAll(label) {
		println(label);
		this.forEach(nextElem => println(nextElem.toString()));
	}
} _br_ _br_// Print All
let array = Mathematician.newSampleSet1();
let qarray = QueryArray.from(array);
qarray.forEach(next => println(next.toString()));