# CC-09: Array Mutations

with Carmen Salas • 2024/10/17

## Code Challenge

1. Declare a function named `replaceWithYerr` that accepts three arguments: an Array, a start index, and the number of elements to replace with the string 'yerr'. The function should return a **new** Array, with the same elements as the original Array, except elements at the starting index, are replaced with the string 'yerr'. The number of elements replaced is determined by the third argument. Implement this function without using `.splice()`.

```js
const replaceWithYerr = (arr, start, num) => {
  let res = [...arr];
  for (; num > 0; num--) {
    res[start++] = "yerr";
  }
  return res;
}

// const months = ['Jan', 'February', 'March', 'April', 'May', 'June'];    
// console.log(`test case:`);
// console.log(replaceWithYerr(months, 1, 3)) //['Jan', 'yerr', 'yerr, 'yerr', 'May', 'June']k
// console.log(`checking original arr:`);
// console.log(months);
```

**Bonus**: Refactor your function so that the second and third arguments are _optional_. If the third argument is missing, the function should return a new array that replaces all elements from the starting index to the end of the array. If only an one argument is passed, it should return a new array argument, with all elements replaced that is the same length as the input array.

```js
const replaceWithYerr2 = (arr, start=0, num=arr.length) => {
  let res = [...arr];
  for (; num > 0; num--) {
    res[start++] = "yerr";
  }
  return res;
}

// const months2 = ['Jan', 'February', 'March', 'April', 'May', 'June'];
// console.log(`first case:`);
// console.log(replaceWithYerr2(months2, 1)) //['Jan', 'yerr', 'yerr, 'yerr', 'yerr', 'yerr']
// console.log('second case:');
// console.log(replaceWithYerr2(months2)) //['yerr', 'yerr', 'yerr, 'yerr', 'yerr', 'yerr']
// console.log(`checking original array:`);
// console.log(months);
```
