Given: we have instance variable that is fixed collection named "this.elements" /**Returns new collection using mapFct to produce new elements */ function mapElements( mapFct) Let newElements = new dynamic (growable) array Iterate over collection "this.elements" (let "next" be the iteration variable) Let newElement = mapFct(next) Add newElement to newElements Return newElements
/** * Returns new QueryArray where1mapFct is used to generate * new elements from existing elements in "this" object */ map(mapFct) { let newElements = Array.newDynamic(); for (let nextElem of2this.elements) { let newElem = mapFct(nextElem); newElements.add(newElem); } return QueryArray.from(newElements); }
class QueryArray { //--------------------------------- //Constructors static from(elements) { return new this(elements); } constructor(elements) { this.elements = elements; } //--------------------------------- //Core forEach(actionFct) { for (let nextElem of this.elements) actionFct(nextElem); } toString() { return this.elements.toString(); } printAll(label) { println(label); this.forEach(nextElem => println(nextElem.toString())); } //--------------------------------- //Utility map(mapFct) { let newElements = Array.newDynamic(); for (let nextElem of this.elements) { let newElem = mapFct(nextElem); newElements.add(newElem); } return QueryArray.from(newElements); } } _br_ _br_//Test It //Map into array of what person is "known for" let array = Mathematician.1newSampleSet1(); let qarray = QueryArray.2from(array); let knownFor = qarray.3map(next => next.getFullName() + " - " + next.getKnownFor()); knownFor.4printAll();