Overview



Code


Convenience Method printAll 💡
Printing is one of the most common operations we do with an array (especially during the development stage).

But every time we print an array we need to write iteration code.

Let's make that easier by adding a QueryArray instance method printAll and employ the new method forEach.
/** Prints all elements to console (with newline after each */
printAll(listLabel) {
	println(listLabel);
	this.forEach(nextElem => println(nextElem.toString()));
}
Try It - printAll
Now we can just call the QueryArray method printAll.
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_//Try It
let array = Mathematician.newSampleSet1();
let qarray = QueryArray.from(array);
qarray.printAll('-- All Mathematicians --');