Skip to content

Instantly share code, notes, and snippets.

@col3name
Created June 13, 2023 15:32
Show Gist options
  • Select an option

  • Save col3name/3c7f509551c387f8b3fd2cc98fd81945 to your computer and use it in GitHub Desktop.

Select an option

Save col3name/3c7f509551c387f8b3fd2cc98fd81945 to your computer and use it in GitHub Desktop.
// 'use strict';
module.exports = async function ({ minPrice, maxPrice, catalog }) {
const activeProducts = [];
async function processCategory(category) {
try {
const isActive = await checkIsActive(category);
if (isActive) {
const children = await getChildren(category);
await processChildren(children);
}
} catch (error) {
await processCategory(category);
}
}
async function processProduct(product) {
try {
const isActive = await checkIsActive(product);
if (isActive) {
const price = await getPrice(product);
if (price >= minPrice && price <= maxPrice) {
const name = await getName(product);
activeProducts.push({ name, price });
}
}
} catch (error) {
await processProduct(product);
}
}
async function processChildren(children) {
await Promise.all(children.map(child => {
if (child instanceof Category) {
return processCategory(child);
}
if (child instanceof Product) {
return processProduct(child);
}
return Promise.resolve();
}))
}
async function checkIsActive(item) {
return new Promise((resolve, reject) => {
item.checkIsActive((error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}
async function getChildren(category) {
return new Promise((resolve, reject) => {
category.getChildren((error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}
async function getName(item) {
return new Promise((resolve, reject) => {
item.getName((error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}
async function getPrice(product) {
return new Promise((resolve, reject) => {
product.getPrice((error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
}
await processCategory(catalog);
activeProducts.sort((a, b) => {
if (a.price === b.price) {
return a.name.localeCompare(b.name);
}
return a.price - b.price;
});
return activeProducts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment