Skip to content

Instantly share code, notes, and snippets.

@DevMasterX
Created November 20, 2024 21:48
Show Gist options
  • Save DevMasterX/4d6fce0dd8cfdef32c8ed68fe8848875 to your computer and use it in GitHub Desktop.
Save DevMasterX/4d6fce0dd8cfdef32c8ed68fe8848875 to your computer and use it in GitHub Desktop.
MODULE - Universal Code for Creating Collections
function createCollection(arr, list, options = {}) {
const {
template,
emptyMessage = 'No items to display.',
emptyImage = '',
} = options;
if (!Array.isArray(arr)) {
throw new Error('Invalid argument: "arr" should be an array.');
}
if (!(list instanceof HTMLElement)) {
throw new Error('Invalid argument: "list" should be a valid DOM element.');
}
if (typeof template !== 'function') {
throw new Error('Invalid argument: "template" should be a function.');
}
// Generate markup for the collection
const markup = arr.length
? arr.map(item => template(item)).join('')
: `
<li class="empty">
${
emptyImage
? `<img src="${emptyImage}" alt="No items" width="600" />`
: ''
}
<p>${emptyMessage}</p>
</li>
`;
// Render the collection
list.innerHTML = markup;
}
export { createCollection };
// USAGE;
// import { createCollection } from './createCollection.js';
// const listElement = document.querySelector('#product-list');
// const products = [
// {
// id: 1,
// img: 'https://example.com/image1.jpg',
// name: 'Product 1',
// price: '$10',
// },
// {
// id: 2,
// img: 'https://example.com/image2.jpg',
// name: 'Product 2',
// price: '$20',
// },
// ];
// // Шаблон для рендера карточек
// const productTemplate = ({ id, img, name, price }) => `
// <li data-id="${id}" class="product-card">
// <img src="${img}" alt="${name}" width="300" />
// <h2>${name}</h2>
// <p>Price: ${price}</p>
// <button class="add-to-cart">Add to Cart</button>
// </li>
// `;
// // Генерация коллекции
// createCollection(products, listElement, {
// template: productTemplate,
// emptyMessage: 'No products available.',
// emptyImage: 'https://example.com/empty.jpg',
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment