Home > OS >  Solving Recursive Product of Array without .slice()
Solving Recursive Product of Array without .slice()

Time:10-12

I was given the advice to not to rely on built in javascript functions when solving Data Structures and Algorithm questions for interview prep and I am having a problem with my code. Here is the original question with my original solution.

Write a recursive function called productOfArray which takes in an array of numbers and returns the product of them all. Examples

// productOfArray([1,2,3]) // 6 // productOfArray([1,2,3,10]) // 60

function productOfArray(arr) {
if(arr.length === 0) {
    return 1;
}
return arr[0] * productOfArray(arr.slice(1)); }

I have tried making my own function to replace the .slice below but to no avail … Thank You all for your time and help. PS .. What are your thoughts on built in methods while studying for an interview? Thanks !

  function productOfArray(arr) {
     function arrSliced(arr, begin, end) {

    let slicedArray = [];

    if (end === null || end > arr.length) {
      end === arr.length;
    }

    for (let i = begin; i < end; i  ) {
      slicedArray.push(arr[i]);
    }
  }

  if (arr.length === 0) {
    return 1;
  }

  return arr[0] * arrSliced(productOfArray, 1);
}

let test = productOfArray([1, 2, 3]);
console.log(test);

CodePudding user response:

Destructuring can do the job:

function productOfArray(arr) {
  if (arr.length === 0) {
    return 1;
  }

  const [head, ...tail] = arr;

  return head * productOfArray(tail);
}

Now, head is the first element, and tail is the rest.

CodePudding user response:

Fixed your code

function productOfArray(arr) {
  function arrSliced(arr, begin, end) {
    const slicedArray = [];

    // if end is not provided it will be undefined not null
    if (end === undefined || end > arr.length) {
      // = is assignment, === is comparison
      end = arr.length;
    }

    for (let i = begin; i < end; i  ) {
      slicedArray.push(arr[i]);
    }

    // you have to return the new array
    return slicedArray
  }

  if (arr.length === 0) {
    return 1;
  }

  // you tried to pass the function here instead of array
  return arr[0] * productOfArray(arrSliced(arr, 1));
}

let test = productOfArray([1, 2, 3]);
console.log(test);

  • Related