Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript how to build array from nested Object using recursion without mutation

interface SubscriptionParams {
  selectedProduct?: SubscriptionSelectedProduct;
}

interface SubscriptionSelectedProduct {
  productId?: string;
  pricingId?: string;
  childProduct?: SubscriptionSelectedProduct;
}

function getChildIdRecursively(product: SubscriptionSelectedProduct, ids: string[]) {
  if (product) {
    ids.push(product.productId!);
    product.childProduct && getChildIdRecursively(product.childProduct, ids);
  }
}

function subscriptionProductsIds(subscription: SubscriptionParams): string[] {
  let ids: string[] = [subscription.selectedProduct?.productId!];
  if (subscription.selectedProduct?.childProduct) {
    getChildIdRecursively(subscription.selectedProduct?.childProduct, ids);
  }

  return ids;
}

How to make this recursion without mutation, now I am mutating ids array.
I want to follow functional programming principles

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’d avoid creating a lot of unnecessary intermediate arrays, but to each their own. Making this "immutable" is as easy as returning a new array from the getChildIdRecursively. Also since you are basically duplicating the logic in subscriptionProductsIds you can remove that.

function getChildIdRecursively(product: SubscriptionSelectedProduct) {
  if (product) {
    let ids: string[] = [product.productId!];
    if (product.childProduct) {
      ids = ids.concat(getChildIdRecursively(product.childProduct));
    }
    return ids;
  }
  return [];
}

function subscriptionProductsIds(subscription: SubscriptionParams): string[] {
  return getChildIdRecursively(subscription.selectedProduct)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading