Why .splice not working in Functional Programming?

Here is something that I check in my chrome console,

1

I’m working with the problem known as, Functional Programming: Understand the Hazards of Using Imperative Code
According to this,

var videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']);

My issue,
2

Why I’m getting tabsAfterIndex is empty? :confused:
(I’m expecting Vine )

try to console.log both this.tabs and index before and after after each use of splice

1 Like

Here is a great example why you should avoid mutating methods like splice. What happens, is that splice is cutting straight from the original array. Therefore your second .splice happens to an already shorter array.

It would be better to use slice. It cuts out and returns a piece of the array, but leaves the original one intact. So you can cut out another piece (using you index variable) and it will work exactly how you expect it to.
So moral of the story – do not use methods that modify original data. Always create new state, do not mutate old state. This is also one of the basic concepts of functional programming and if you choose to follow it, you will avoid a LOT of potential errors in your programming journey.

2 Likes

Exactly! :grin:
This is how I fix this. Is that a good way?

  var copy = [...this.tabs];
  var tabsBeforeIndex = copy.splice(0, index); // Get the tabs before the tab
  var tabsAfterIndex = copy.splice((index-tabsBeforeIndex.length) + 1); // Get the tabs after the tab
  this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // Join them together
1 Like

:+1: This resolves error. But it requires an additional calculation that is not necessary. Here is an example with slice :slight_smile:

var beforeTabs = this.tabs.slice(0, index) // get elements up to index (not included)
var afterTabs = this.tabs.slice(index+1) // get elements from i+1 until the end of list
this.tabs = beforeTabs.concat(afterTabs)

// or example as a one-liner (shorter does not mean better, often it is worse as far as readability goes)
this.tabs = [...this.tabs.slice(0, index), ...this.tabs.slice(index + 1)] 
2 Likes

Okay, I understand. So, if I use slice I don’t need to [...this.tabs] and this (index-tabsBeforeIndex.length) calculation.
Thank you so much :hugs:

1 Like

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