I am trying an example for chain of responsibility but I dont fully understand the code. Here is the small json I use
{
"design": [
{"name": "Photoshop", "price": 5},
{"name": "After Effect", "price": 15},
{"name": "Sketch", "price": 10}
],
"language": [
{"name": "English", "price": 53},
{"name": "French", "price": 54},
{"name": "German", "price": 60}
],
"music": [
{"name": "F1 Studio", "price": 71},
{"name": "Adobe Audition", "price": 42},
{"name": "DJ", "price": 47}
]
}
And here is the code:
const courses = require('./courses.json');
class Category {
constructor (name, courses = []){
this.name = name;
this.courses = courses;
this.next = null;
}
setNext(categoryName){
this.next = categoryName;
}
search(itemName){
const index = this.courses.map(item => item.name).indexOf(itemName);
const found = this.courses[index];
if (found) {
return {
name: found.name,
price: found.price,
location: this.name
}
} else if (this.next) {
return this.next.search(itemName);
} else {
return `${itemName} not found`;
}
}
}
class Finder {
constructor(name, courses = []){
this.name = name;
this.courses = courses;
const design = new Category('design', courses.design);
const language = new Category('language', courses.language);
const music = new Category('music', courses.music);
design.setNext(language);
language.setNext(music);
this.category = design;
}
find(itemName) {
return this.category.search(itemName);
}
}
const result = new Finder('my course', courses).find('DJ');
console.log(result);
My problem I dont understand how setNext
method work and why it is called in the constructor. Also I found that this
changes in this line return this.next.search(itemName);
how this is possible ?