TopicIterator
by Rolf
HTML
<ol id="results">
</ol>
JavaScript
class TopicIterator {
constructor() {
}
search(accessor) {
if (!(accessor instanceof Function))
throw new TypeError("Invalid parameter, pass a function")
this._getTopics = accessor;
return this;
}
forAll(...topics) {
if (topics.length == 0)
throw new TypeError("Specify at least one topic!");
if (this._isRelevant)
throw new TypeError("Specify your topics only once!");
this._isRelevant = itemTopics => topics.every(topic => itemTopics.includes(topic));
return this;
}
forAny(...topics) {
if (topics.length == 0)
throw new TypeError("Specify at least one topic!");
if (this._isRelevant)
throw new TypeError("Specify your topics only once!");
this._isRelevant = itemTopics => topics.some(topic => itemTopics.includes(topic));
return this;
}
// Beachte den Stern, diese Methode ist ein Generator!
*in(collection) {
if (!collection || !collection[Symbol.iterator])
throw new TypeError("Cannot iterate data");
if (!this._getTopics)
throw new TypeError("Specify search location (call search method and pass an accessor function)");
if (!this._isRelevant)
throw new TypeError("Specify topics to find (call forAll or forAny and pass them)");
for (let item of collection) {
if (this._isRelevant(this._getTopics(item)))
yield item;
}
}
}
// Spieldaten
let itemList = [
{ name: "Hugo", topics: [ "Foo", "Baz" ] },
{ name: "Otto", topics: [ "Foo", "Bar" ] },
{ name: "Paul", topics: [ "Bar", "Foo", "Baz" ] },
];
try {
// Die eigentliche Suche!
// In found findet sich ein iterierbares Objekt (eine Generatorfunktion),
// die die Ergebnisse liefert
let found = new TopicIterator()
.search(item => item.topics)
.forAll()
.in(itemList);
// Aufbereitung der Treffer in der Ordered List
let results =...