Dodajemy kolejne utils – tym razem do pracy na obiektach. Chcemy robić kopie obiektów zamiast modyfikacji już istniejących.
Na początek funkcja objectWithout:
function objectWithout(obj, property){
let {[property]: removed, ...without} = obj;
return without;
}
let obj = {
name: "blabla",
age: 30,
}
let obj2 = objectWithout(obj, "age");
console.log(obj2);
//Object { name: "blabla" }
Analogiczna funkcja objectWith:
function objectWith(obj, property, value){
return {...obj, [property] : value};
}
let obj3 = objectWith(obj, "id", 3);
console.log(obj3);
//Object { name: "blabla", age: 30, id: 3 }
Teraz objectWithUpdated:
function objectWithUpdated(obj, property, value){
let {[property]: removed, ...without} = obj;
return {[property]: value, ...without};
}
let obj4 = objectWithUpdated(obj3, "id", 4);
console.log(obj4);
//Object { id: 4, name: "blabla", age: 30 }
Na koniec objectWithMutated:
function objectWithMutated(obj, property, cb){
let {[property]: removed, ...without} = obj;
let value = cb(removed);
return {[property]:value, ...without};
}
let obj5 = objectWithMutated(obj4, "id", (id) => id+1);
console.log(obj5);
//Object { id: 5, name: "blabla", age: 30 }
Więcej utils wkrótce.