Overview



Code


Method findFirst
We add this method to the class QueryArray.

Just a couple tweaks of our previous work are necessary:

  • Shorten the param list
  • Access the ivar this.elements

With objects the keyword this is big.
/** Returns the index of the first match, or -1 if no match */
findFirst(
1
matchFct) { let elements =
2
this.elements; for (let i = 0; i < elements.length; i++) { let nextElem = elements.get(i); if (matchFct(nextElem)) return i; } return -1; }
Try It - findFirst
Explanation of example usage:

  • Construct array using helper
  • Construct QueryArray of mathematicians
  • Find index of first object with country "Kenya"
  • Print result
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 - map into array of countries

let array = Mathematician.
1
newSampleSet1(); let qarray = QueryArray.
2
from(array); qarray.printAll(); let matchIndex = qarray.
3
findFirst(next => next.getCountry().equals('Kenya'));
4
println("\nIndex of first match: " + matchIndex);