Код: Выделить всё
let products = []; //Array where transformed data from fetch request is stored for further use
function getProduct(productId) {//function to get product with certain id
let matchProduct = products.find(product => product.id === productId)
return matchProduct;
}
class Product { /*Example of classes used in function below, I can test them fine and they pass tests*/
id;
image;
name;
rating;
priceCents;
keywords;
constructor(productDetails) {
this.id = productDetails.id;
this.image = productDetails.image;
this.name = productDetails.name;
this.rating = productDetails.rating;
this.priceCents = productDetails.priceCents;
this.keywords = productDetails.keywords;
}
getStars() {
return `images/ratings/rating-${this.rating.stars * 10}.png`;
}
getPrice() {
return `$${formatCurrency(this.priceCents)}`;
}
extraInfoHTML() {
return ''
}
}
function loadProducts() {
const promise = fetch('link to host').then(response => {
return response.json(); //host responds with array of objects if translated in json
}).then(productData => { /*manipulating received array of objects to transform objects into classes and saving in new array*/
products = productData.map(productDetails => {
if (productDetails.keywords.includes('appliances')) {
productDetails.type = 'appliance';
productDetails.instructionLink = 'images/appliance-instructions.png';
productDetails.warrantyLink = 'images/appliance-warranty.png';
return new Appliance(productDetails);
}
if (productDetails.type === 'clothing') {
return new Clothing(productDetails);
}
return new Product(productDetails);
});
}).catch(error => {
console.error(error.message);
});
return promise;
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... emote-host