I've been learning the fundamentals of Big(o)
and after looking at some old code I've written, I habitually use nested for loops
for problems like this instead of implementing a better approach with a faster run time. For instance:
const webhooks = [
[
{
topic: "CUSTOMERS_CREATE",
path: `${process.env.HOST}/webhooks/customers/create`,
},
{
topic: "CUSTOMERS_UPDATE",
path: `${process.env.HOST}/webhooks/customers/update`,
},
{
topic: "CUSTOMERS_DELETE",
path: `${process.env.HOST}/webhooks/customers/delete`,
},
],
[
{
topic: "CHECKOUTS_CREATE",
path: `${process.env.HOST}/webhooks/checkouts/create`,
},
{
topic: "CHECKOUTS_UPDATE",
path: `${process.env.HOST}/webhooks/checkouts/update`,
},
],
[
{
topic: "ORDERS_CREATE",
path: `${process.env.HOST}/webhooks/orders/create`,
},
{
topic: "ORDERS_UPDATED",
path: `${process.env.HOST}/webhooks/orders/update`,
},
{
topic: "ORDERS_DELETE",
path: `${process.env.HOST}/webhooks/orders/delete`,
},
],
[
{
topic: "PRODUCTS_CREATE",
path: `${process.env.HOST}/webhooks/products/create`,
},
{
topic: "PRODUCTS_UPDATE",
path: `${process.env.HOST}/webhooks/products/update`,
},
{
topic: "PRODUCTS_DELETE",
path: `${process.env.HOST}/webhooks/products/delete`,
},
],
];
// Registering the webhooks
webhooks.forEach(async (elm) => {
elm.forEach(async (el) => {
Shopify.Webhooks.Registry.addHandler(el.topic, {
path: el.path,
webhookHandler: webhookController,
});
});
});
In this snippet, I am looping over the initial array, then the nested array to finally get the topic
and path
for each element. Then I make a function call with those properties for further processing. While a nested for loop
works, I know it will have a runtime of O(n^2)
which is awful at scale. I thought about converting this array of objects into a map, but are there caveats to this approach I'm missing? If so, what alternative methods could I use to achieve a much more ideal runtime like O(log(n))
?