Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

93
Views
Is there a faster way to loop through nested array of objects than nested for loops?

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))?

6 months ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.