Skip to content
Advertisement

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

Advertisement

Answer

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)
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement