Functional Programming - Refactor Global Variables Out of Functions

Tell us what’s happening:
My remove function does not pass the tests. As far as I can tell, I am not changing the original array bookList. When I run my code in Chrome’s Javascript console, I am able to get the correct result. Could someone point out where my code has gone wrong? Thanks!

Your code so far

// The global variable
const bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];

// Change code below this line
function add(arg, bookName) {
  const newArray = arg.concat(bookName);
  return newArray;
  // Change code above this line

// Change code below this line
function remove(arg, bookName) {
  let newArray = [...arg];
  const index = newArray.indexOf(bookName);
  if (index >= 0) {
    newArray = newArray.toSpliced(index, 1);
    return newArray;
    // Change code above this line

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/114.0

Challenge: Functional Programming - Refactor Global Variables Out of Functions

Link to the challenge:

Hello brkfst,

Welcome to the forums,
Why dont you try to use splice instead of toSpliced?

Hi krze.tomas, thanks for the suggestion.
Could you kindly explain why toSpliced would not work?
I am open to using splice. (My goal is to understand the code, not just to pass the test.)

Hello again,
I did not say toSpliced would not work, but I have suggested this on the structure of your code. As because the toSpliced is the immutable version of spliced. Which means that it will return a new array instead of changing the original. But when I have seen the line in your code where you state:

let newArray = [...arg];

You are already making a copy of the original array, so I assumed you can splice this local copy and return it

1 Like

Sorry forgot to add:
The reason why it is not working is probably because it is asynchronous. The array is being returned before it is processed. Just try to give the toSpliced method in a console log inside your function to see if it is working.

console.log( newArray.toSpliced(index, 1));

then try to return the array with the method, instead of using the method and then returning the array on the next line.

return arg.toSpliced(book_index, 1)

Firefox 114 does not support toSpliced, 115 does.

The dev version should support it

1 Like

Thanks for your input. First time I had downloaded a dev version of anything :slight_smile:
The code with toSpliced is now working in Firefox dev version and Chrome. :+1:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.