Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to double these numbers in an array using recursion, rest/spread operators and destructuring?

I recently completed a JavaScript challenge asking to return a new array with all the values of the initial array doubled.

const numbers = [1, 2, 3];

function double() {

}

Except that I was to include some ES6 topics of de-structuring and rest/spread operators as well as recursion. Well, I completed as best as I could to come to a solution. This was my solution:

const numbers = [1, 2, 3];

function double(arr){
 const doubledNumbers = [];
 for (var i = 0; i < arr.length; i ++){
  const dubba = arr[i];
  const bubba = dubba * 2;
   doubledNumbers.push(bubba);
 }
 return doubledNumbers;

}

The other requirement was to not use any array helper method (map, reduce etc), so I did not use map(), but instead a for loop. However, I could not wrap my head around implementing de-structuring or rest/spread operators, concepts I thought I knew pretty well, never-mind recursion.

like image 993
Daniel Avatar asked Jan 02 '23 13:01

Daniel


1 Answers

Here's one possible implementation - destructure the parameter of double, taking out the first number in the array, and use rest syntax to put the rest of the numbers into another array. Then, double the rest of the array, and spread it into a new (returned) array, headed by the first number times 2:

const numbers = [1, 2, 3];

function double([firstNum, ...rest]) {
  const restDoubled = rest.length ? double(rest) : [];
  return [firstNum * 2, ...restDoubled];
}

console.log(double(numbers));
like image 118
CertainPerformance Avatar answered Jan 04 '23 04:01

CertainPerformance