const numbers = [1, 2, 3];
# Adding
const index = numbers.indexOf(2);
const added = [...numbers.slice(0, index), 4, ...numbers.slice(index)];
console.log(added);
[ 1, 4, 2, 3 ]
# Removing
const removed = numbers.filter((n) => n !== 2);
console.log(removed);
[ 1, 3 ]
# Updating
const updated = numbers.map((n) => (n === 2 ? 20 : n));
console.log(updated);
[ 1, 20, 3 ]
let book = { title: "Harry Potter" };
function publish(book) {
book.isPublished = true;
}
publish(book);
console.log(book);
{ title: 'Harry Potter', isPublished: true }
--
let book = Map({ title: "Harry Potter" });
console.log(book.get("title"));
Harry Potter
import { Map } from "immutable";
let book = Map({ title: "Harry Potter" });
function publish(book) {
return book.set("isPublished", true);
}
book = publish(book);
console.log(book.toJS());
import { produce } from "immer";
let book = { title: "Harry Potter" };
function publish(book) {
return produce(book, (draftBook) => {
draftBook.isPublished = true;
});
}
let updated = publish(book);
console.log(book); { title: 'Harry Potter' }
console.log(updated); { title: 'Harry Potter', isPublished: true }
bugs랑 currenUser 가 reducer
{
bugs: [
{
id: 1,
description: "",
resolved: false,
},
];
currentUser: {
}
}
{
type: "ADD_BUG",
description: "..."
}
{
type: "bugAdded",
payload : {
id:1
}
}
/// []
let lastId = 0;
function reducer(state = [], action) {
if (action.type === "bugAdded")
return [
...state,
{
id: ++lastId,
description: action.payload.description,
resolved: false,
},
];
else if (actiony.type === "bugRemoved")
return state.filter((bug) => bug.id !== action.payload.id);
return state;
}
-reducer.js
export default function reducer(state = [], action) {
switch (action.type) {
case "bugAdded":
return [
...state,
{
id: ++lastId,
description: action.payload.description,
resolved: false,
},
];
case "bugRemoved":
return state.filter((bug) => bug.id !== action.payload.id);
default:
return state;
}
}
-store.js
import { createStore } from "redux";
import { reducer } from "./reducer";
const store = createStore(reducer);
export default store;