There should be another functional approach for this challenge?

The beginning of the challenge says:
But before we get there, let's look at an imperative approach to programming to highlight where you may have issues.
So I’m assuming the solution provided in the challange is an imperative approach and as the title indicated, we’re trying to understand the hazards of using imperative code.

Since there’s potential hazards, I believe we’re encouraged to use functional programming instead, that has minimal side effect. So does it mean that there is a functional approach for this challenge?

var Window = function(tabs) {
 this.tabs = tabs; 
};

Window.prototype.join = function (otherWindow) {
 this.tabs = this.tabs.concat(otherWindow.tabs);
 return this;
};

Window.prototype.tabOpen = function (tab) {
 this.tabs.push('new tab');
 return this;
};

Window.prototype.tabClose = function (index) {

 var tabsBeforeIndex = this.tabs.splice(0, index);
 var tabsAfterIndex = this.tabs.splice(1);
 this.tabs = tabsBeforeIndex.concat(tabsAfterIndex);
 return this;
};

var workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']);
var socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']);
var videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']);

var finalTabs = socialWindow
 .tabOpen()
 .join(videoWindow.tabClose(2))
 .join(workWindow.tabClose(1).tabOpen());
console.log(finalTabs.tabs);
   **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38

Challenge: Understand the Hazards of Using Imperative Code

Link to the challenge:

Yes. From the docs:

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

So you’d want to use some other approach than splice because you don’t want to modify the array in place.

On the other hand, concat is safe:

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

So I’d say the goal is to use a different approach than splice here.

1 Like

Do you mean the original (problematic) solution is an example of imperative approach and after replacing splice with the slice method the whole solution can be considered a functional approach?

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