Adds intermediate solution and corrects "run code" link (#18601)
* Correct "Run Code Link" Currently when the user hits "Run Code" they are brought to a repl that shows a function for `reverseString`. I just copied the code from the explanation into a new repl and linked that so when users click "Run code" they are taken to the correct code. * Adds an intermediate solution Since submitting my last PR on this page I have verified that my intermediate solution works, it eliminates the need for the `for` loop. * fix: formatting
This commit is contained in:
@ -39,18 +39,18 @@ Increment the index after performing the splice.
|
||||
**Solution ahead!**
|
||||
|
||||
##  Basic Code Solution:
|
||||
|
||||
function frankenSplice(arr1, arr2, n) {
|
||||
// It's alive. It's alive!
|
||||
let localArray = arr2.slice();
|
||||
for (let i = 0; i < arr1.length; i++) {
|
||||
localArray.splice(n, 0, arr1[i]);
|
||||
n++;
|
||||
}
|
||||
return localArray;
|
||||
}
|
||||
|
||||
 <a href='https://repl.it/CLjU' target='_blank' rel='nofollow'>Run Code</a>
|
||||
```js
|
||||
function frankenSplice(arr1, arr2, n) {
|
||||
// It's alive. It's alive!
|
||||
let localArray = arr2.slice();
|
||||
for (let i = 0; i < arr1.length; i++) {
|
||||
localArray.splice(n, 0, arr1[i]);
|
||||
n++;
|
||||
}
|
||||
return localArray;
|
||||
}
|
||||
```
|
||||
 <a href='https://repl.it/repls/RedundantGrossGenres' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
### Code Explanation:
|
||||
|
||||
@ -64,6 +64,24 @@ Increment the index after performing the splice.
|
||||
|
||||
* Finally, we return the `localArray` and end the function.
|
||||
|
||||
|
||||
## 🌻 Intermediate Code Solution:
|
||||
```js
|
||||
function frankenSplice(arr1, arr2, n) {
|
||||
// It's alive. It's alive!
|
||||
let localArr = arr2.slice();
|
||||
localArr.splice(n, 0, ...arr1);
|
||||
return localArr;
|
||||
}
|
||||
```
|
||||
 <a href='https://repl.it/repls/BelovedNegativeMoto' target='_blank' rel='nofollow'>Run Code</a>
|
||||
|
||||
* Since our goal is to return the new array with out altering `arr1` or `arr2` we create a `localArr` and add all the items from `arr2` using the `slice()` function
|
||||
|
||||
* Since the `splice()` function will mutate (alter) arrays and can be used to add new elements we will use it to add the contents of `arr1` into `localArr`. `n` is the starting position where our content will be inserted. We won't be deleting any elements so the next argument is `0`. Then we add the entire contents of `arr1` using spread syntax `...`.
|
||||
|
||||
* `localArr` is returned and the function is complete.
|
||||
|
||||
##  NOTES FOR CONTRIBUTIONS:
|
||||
|
||||
*  **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
|
||||
|
Reference in New Issue
Block a user