Replacing an Array item by Index with Refactoring Example

John Peters - Sep 1 '20 - - Dev Community

Photo courtesy of DreamsTime

Original Code

let items = ["one","two","three"];
let newValue = "four";
let found = items.find(item=>item==="two");
let index = items.indexOf(found);
items.splice(index,1,newValue);
Enter fullscreen mode Exit fullscreen mode

First Mutable Refactor

// mutable example
function replace(items, currentValue, newValue){
  let found = items.find(item=>item===currentValue);
  let index = items.indexOf(found);
  items.splice(index,1,newValue);
}
Enter fullscreen mode Exit fullscreen mode

Second Immutable Refactor

// immutable example
function replace(items,currentValue, newValue):[]{
  let list = [...items];
  let found = list.find(item=>item===currentValue);
  let index = list.indexOf(found);
  list.splice(index,1,newValue);
  return list;
}
Enter fullscreen mode Exit fullscreen mode

What would the last refactor look like? Let us know in comments below.

JWP2020 Replacing Items in an Array

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player