Refactored CREATE_FILE and UPDATE_FILE_NAME case into smaller functions

This commit is contained in:
Neelesh 2020-08-04 10:28:21 +05:30
parent 855dceaafe
commit 4b022dd0e8

View file

@ -116,6 +116,26 @@ function sortedChildrenId(state, children) {
return childrenArray.map(child => child.id); return childrenArray.map(child => child.id);
} }
function udpateParent(state, action) {
return state.map((file) => {
if (file.id === action.parentId) {
const newFile = Object.assign({}, file);
newFile.children = [...newFile.children, action.id];
return newFile;
}
return file;
});
}
function renameFile(state, action) {
return state.map((file) => {
if (file.id !== action.id) {
return file;
}
return Object.assign({}, file, { name: action.name });
});
}
const files = (state, action) => { const files = (state, action) => {
if (state === undefined) { if (state === undefined) {
state = initialState(); // eslint-disable-line state = initialState(); // eslint-disable-line
@ -144,16 +164,8 @@ const files = (state, action) => {
return initialState(); return initialState();
case ActionTypes.CREATE_FILE: // eslint-disable-line case ActionTypes.CREATE_FILE: // eslint-disable-line
{ {
let newState = state.map((file) => { const newState = [
if (file.id === action.parentId) { ...udpateParent(state, action),
const newFile = Object.assign({}, file);
newFile.children = [...newFile.children, action.id];
return newFile;
}
return file;
});
newState = [
...newState,
{ {
name: action.name, name: action.name,
id: action.id, id: action.id,
@ -161,9 +173,8 @@ const files = (state, action) => {
content: action.content, content: action.content,
url: action.url, url: action.url,
children: action.children, children: action.children,
fileType: action.fileType || 'file', fileType: action.fileType || 'file'
}, }];
];
return newState.map((file) => { return newState.map((file) => {
if (file.id === action.parentId) { if (file.id === action.parentId) {
file.children = sortedChildrenId(newState, file.children); file.children = sortedChildrenId(newState, file.children);
@ -173,12 +184,7 @@ const files = (state, action) => {
} }
case ActionTypes.UPDATE_FILE_NAME: case ActionTypes.UPDATE_FILE_NAME:
{ {
const newState = state.map((file) => { const newState = renameFile(state, action);
if (file.id !== action.id) {
return file;
}
return Object.assign({}, file, { name: action.name });
});
return newState.map((file) => { return newState.map((file) => {
if (file.children.includes(action.id)) { if (file.children.includes(action.id)) {
file.children = sortedChildrenId(newState, file.children); file.children = sortedChildrenId(newState, file.children);