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

Time:11-26

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

CodePudding user response:

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)
}
  • Related