Quick Index
Overview



Algorithm



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


Pseudocode


Method mapElements
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 new QueryArray where 
1
mapFct is used to generate * new elements from existing elements in "this" object */
map(mapFct) { let newElements = Array.newDynamic(); for (let nextElem of
2
this.elements) { let newElem = mapFct(nextElem); newElements.add(newElem); } return QueryArray.from(newElements); }
Try It - map
Explanation of example usage:

  • Construct array using helper
  • Construct QueryArray of mathematicians
  • Map objects to "name-known for" strings
  • Print entire list
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.
1
newSampleSet1(); let qarray = QueryArray.
2
from(array); let knownFor = qarray.
3
map(next => next.getFullName() + " - " + next.getKnownFor()); knownFor.
4
printAll();