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);
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);
}
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;
}
What would the last refactor look like? Let us know in comments below.
JWP2020 Replacing Items in an Array
Top comments (0)